#!/bin/bash
#
# GALA-5.8: Find Old Namespace Imports
#
# Script to find remaining `use App\Model\Event` imports across the codebase.
# Helps track progress of namespace migration from Event to Gala.
#
# Usage:
#   ./bin/find-old-namespaces.sh           # Full report
#   ./bin/find-old-namespaces.sh --count   # Just counts
#   ./bin/find-old-namespaces.sh --json    # JSON output for CI
#
# Exit codes:
#   0 - No old imports found (migration complete)
#   1 - Old imports still exist (migration in progress)
#

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Parse arguments
COUNT_ONLY=false
JSON_OUTPUT=false

for arg in "$@"; do
    case $arg in
        --count)
            COUNT_ONLY=true
            ;;
        --json)
            JSON_OUTPUT=true
            ;;
        --help|-h)
            echo "Usage: $0 [--count] [--json]"
            echo ""
            echo "Find remaining 'use App\\Model\\Event' imports in the codebase."
            echo ""
            echo "Options:"
            echo "  --count   Show only counts, no file details"
            echo "  --json    Output as JSON (for CI integration)"
            echo ""
            exit 0
            ;;
    esac
done

cd "$PROJECT_ROOT"

# Function to count matches in a directory
count_matches() {
    local dir="$1"
    if [ -d "$dir" ]; then
        grep -rl "use App\\\\Model\\\\Event" "$dir" 2>/dev/null | wc -l | tr -d ' '
    else
        echo "0"
    fi
}

# Function to list files in a directory
list_matches() {
    local dir="$1"
    if [ -d "$dir" ]; then
        grep -rl "use App\\\\Model\\\\Event" "$dir" 2>/dev/null || true
    fi
}

# Gather counts
SERVICES_COUNT=$(count_matches "app/Services")
CONTROLLERS_COUNT=$(count_matches "app/Http/Controllers")
JOBS_COUNT=$(count_matches "app/Jobs")
MAIL_COUNT=$(count_matches "app/Mail")
GALA_SERVICES_COUNT=$(count_matches "app/Domains/Gala/Services")
OTHER_COUNT=$(grep -rl "use App\\\\Model\\\\Event" app/ 2>/dev/null | grep -v -E "(Services|Controllers|Jobs|Mail)" | wc -l | tr -d ' ')
TOTAL_COUNT=$((SERVICES_COUNT + CONTROLLERS_COUNT + JOBS_COUNT + MAIL_COUNT + OTHER_COUNT))

# Count new namespace usage
NEW_NAMESPACE_COUNT=$(grep -rl "use App\\\\Domains\\\\Gala\\\\Models\\\\Gala" app/ 2>/dev/null | wc -l | tr -d ' ' || echo "0")

if [ "$JSON_OUTPUT" = true ]; then
    # JSON output for CI
    cat << EOF
{
  "old_namespace": {
    "pattern": "use App\\\\Model\\\\Event",
    "counts": {
      "services": $SERVICES_COUNT,
      "controllers": $CONTROLLERS_COUNT,
      "jobs": $JOBS_COUNT,
      "mail": $MAIL_COUNT,
      "gala_services": $GALA_SERVICES_COUNT,
      "other": $OTHER_COUNT,
      "total": $TOTAL_COUNT
    }
  },
  "new_namespace": {
    "pattern": "use App\\\\Domains\\\\Gala\\\\Models\\\\Gala",
    "count": $NEW_NAMESPACE_COUNT
  },
  "migration_complete": $([ "$TOTAL_COUNT" -eq 0 ] && echo "true" || echo "false"),
  "intentional_remaining": {
    "jobs": "Keep Event for serialization backward compatibility",
    "mail": "Keep Event for serialization backward compatibility"
  }
}
EOF
    exit $([ "$TOTAL_COUNT" -eq 0 ] && echo 0 || echo 1)
fi

if [ "$COUNT_ONLY" = true ]; then
    echo "=== Old Namespace Import Counts ==="
    echo "app/Services:                $SERVICES_COUNT"
    echo "app/Http/Controllers:        $CONTROLLERS_COUNT"
    echo "app/Jobs:                    $JOBS_COUNT (intentional - serialization)"
    echo "app/Mail:                    $MAIL_COUNT (intentional - serialization)"
    echo "app/Domains/Gala/Services:   $GALA_SERVICES_COUNT"
    echo "Other app/ files:            $OTHER_COUNT"
    echo "---"
    echo "Total old imports:           $TOTAL_COUNT"
    echo "New namespace usage:         $NEW_NAMESPACE_COUNT"
    exit $([ "$TOTAL_COUNT" -eq 0 ] && echo 0 || echo 1)
fi

# Full report
echo -e "${BLUE}=== GALA-5.8: Namespace Migration Report ===${NC}"
echo ""
echo -e "${YELLOW}Old Namespace: use App\\Model\\Event${NC}"
echo ""

echo -e "${BLUE}--- app/Services/ ($SERVICES_COUNT files) ---${NC}"
if [ "$SERVICES_COUNT" -gt 0 ]; then
    list_matches "app/Services" | while read -r file; do
        echo -e "  ${RED}*${NC} $file"
    done
else
    echo -e "  ${GREEN}All migrated to new namespace${NC}"
fi

echo ""
echo -e "${BLUE}--- app/Http/Controllers/ ($CONTROLLERS_COUNT files) ---${NC}"
if [ "$CONTROLLERS_COUNT" -gt 0 ]; then
    list_matches "app/Http/Controllers" | while read -r file; do
        echo -e "  ${RED}*${NC} $file"
    done
else
    echo -e "  ${GREEN}All migrated to new namespace${NC}"
fi

echo ""
echo -e "${BLUE}--- app/Jobs/ ($JOBS_COUNT files) ---${NC}"
if [ "$JOBS_COUNT" -gt 0 ]; then
    echo -e "  ${YELLOW}(Intentionally kept for serialization backward compatibility)${NC}"
    list_matches "app/Jobs" | while read -r file; do
        echo -e "  ${YELLOW}*${NC} $file"
    done
else
    echo -e "  ${GREEN}No Event imports${NC}"
fi

echo ""
echo -e "${BLUE}--- app/Mail/ ($MAIL_COUNT files) ---${NC}"
if [ "$MAIL_COUNT" -gt 0 ]; then
    echo -e "  ${YELLOW}(Intentionally kept for serialization backward compatibility)${NC}"
    list_matches "app/Mail" | while read -r file; do
        echo -e "  ${YELLOW}*${NC} $file"
    done
else
    echo -e "  ${GREEN}No Event imports${NC}"
fi

echo ""
echo -e "${BLUE}--- app/Domains/Gala/Services/ ($GALA_SERVICES_COUNT files) ---${NC}"
if [ "$GALA_SERVICES_COUNT" -gt 0 ]; then
    echo -e "  ${RED}(Should use App\\Domains\\Gala\\Models\\Gala)${NC}"
    list_matches "app/Domains/Gala/Services" | while read -r file; do
        echo -e "  ${RED}*${NC} $file"
    done
else
    echo -e "  ${GREEN}All using Gala domain namespace${NC}"
fi

echo ""
echo -e "${BLUE}=== Summary ===${NC}"
echo -e "Old namespace imports:  ${RED}$TOTAL_COUNT${NC}"
echo -e "New namespace usage:    ${GREEN}$NEW_NAMESPACE_COUNT${NC}"
echo ""

if [ "$TOTAL_COUNT" -eq 0 ]; then
    echo -e "${GREEN}Migration complete! No old namespace imports remaining.${NC}"
    exit 0
else
    echo -e "${YELLOW}Migration in progress. $TOTAL_COUNT files still use old namespace.${NC}"
    echo ""
    echo "Notes:"
    echo "  - Jobs and Mail files should keep Event (serialization safety)"
    echo "  - Gala domain services should migrate first (they own the domain)"
    echo "  - Services and Controllers migrate after Event->Gala alias is established"
    exit 1
fi
