#!/bin/bash
# Migrate repository structure to idiomatic PHP layout

set -e

echo "🔄 Migrating XAMXAM repository structure"
echo "==========================================="
echo ""

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# Check we're in the right directory
if [ ! -d "apps" ] || [ ! -d "shared" ]; then
    echo -e "${RED}Error: Must run from repository root${NC}"
    exit 1
fi

echo -e "${YELLOW}⚠️  This will restructure the repository!${NC}"
echo ""
echo "Changes:"
echo "  • Move apps/public/* to root"
echo "  • Move apps/admin/ to admin/"
echo "  • Rename shared/ to lib/"
echo "  • Update all require paths"
echo "  • Remove apps/ directory"
echo ""
read -p "Continue? [y/N] " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Cancelled"
    exit 1
fi

echo ""
echo "📦 Step 1: Moving public files to root..."
echo "--------------------------------------"

# Move public files to root (exclude those that already exist)
for file in apps/public/*; do
    filename=$(basename "$file")
    if [ "$filename" != "tests" ] && [ "$filename" != "cache" ]; then
        if [ -e "$filename" ]; then
            echo "  ⚠️  Skipping $filename (already exists)"
        else
            mv "$file" .
            echo "  ✓ Moved $filename"
        fi
    fi
done

echo ""
echo "📦 Step 2: Moving admin panel..."
echo "--------------------------------------"

if [ -d "admin" ]; then
    echo "  ⚠️  admin/ already exists, removing it first"
    rm -rf admin/
fi

mv apps/admin admin/
echo "  ✓ Moved apps/admin/ to admin/"

echo ""
echo "📦 Step 3: Renaming shared/ to lib/..."
echo "--------------------------------------"

if [ -d "lib" ]; then
    echo "  ⚠️  lib/ already exists, removing it first"
    rm -rf lib/
fi

mv shared lib/
echo "  ✓ Renamed shared/ to lib/"

echo ""
echo "📦 Step 4: Removing apps/ directory..."
echo "--------------------------------------"

if [ -d "apps" ]; then
    rm -rf apps/
    echo "  ✓ Removed apps/"
fi

echo ""
echo "📦 Step 5: Updating require paths in root PHP files..."
echo "--------------------------------------"

# Update root PHP files
find . -maxdepth 1 -name "*.php" -type f | while read file; do
    if grep -q "shared/" "$file" 2>/dev/null; then
        sed -i "s|__DIR__ \. '/shared/|__DIR__ . '/lib/|g" "$file"
        sed -i "s|'shared/|'lib/|g" "$file"
        sed -i "s|\"shared/|\"lib/|g" "$file"
        echo "  ✓ Updated $file"
    fi
done

echo ""
echo "📦 Step 6: Updating require paths in admin/..."
echo "--------------------------------------"

# Update admin PHP files
find admin/ -name "*.php" -type f | while read file; do
    if grep -q "shared/" "$file" 2>/dev/null; then
        sed -i "s|__DIR__ \. '/\.\./\.\./shared/|__DIR__ . '/../lib/|g" "$file"
        sed -i "s|'../../shared/|'../lib/|g" "$file"
        sed -i "s|\"../../shared/|\"../lib/|g" "$file"
        echo "  ✓ Updated $file"
    fi
done

echo ""
echo "📦 Step 7: Updating lib/config.php paths..."
echo "--------------------------------------"

if [ -f "lib/config.php" ]; then
    # Update database paths in config
    sed -i "s|__DIR__ \. '/\.\.'|__DIR__ . '/..'|g" lib/config.php
    echo "  ✓ Updated lib/config.php"
fi

echo ""
echo "📦 Step 8: Creating vendor directory..."
echo "--------------------------------------"

mkdir -p vendor/
echo "  ✓ Created vendor/"

echo ""
echo "📦 Step 9: Updating .gitignore..."
echo "--------------------------------------"

if ! grep -q "^vendor/" .gitignore 2>/dev/null; then
    echo "vendor/" >> .gitignore
    echo "  ✓ Added vendor/ to .gitignore"
else
    echo "  ⚠️  vendor/ already in .gitignore"
fi

if ! grep -q "^\.DS_Store" .gitignore 2>/dev/null; then
    echo ".DS_Store" >> .gitignore
    echo "  ✓ Added .DS_Store to .gitignore"
fi

echo ""
echo "═══════════════════════════════════════"
echo -e "${GREEN}✅ Migration complete!${NC}"
echo "═══════════════════════════════════════"
echo ""
echo "📋 Next steps:"
echo "  1. Review changes: git status"
echo "  2. Test locally: just serve-public"
echo "  3. Run tests: just test-public-all"
echo "  4. Commit: git add -A && git commit -m 'Restructure to idiomatic PHP layout'"
echo "  5. Deploy: just deploy"
echo ""
echo "📁 New structure:"
echo "  index.php         - Public root"
echo "  admin/            - Admin panel"
echo "  lib/              - Shared libraries"
echo "  assets/           - Static files"
echo "  inc/              - Templates"
echo "  storage/         - Database files"
echo "  vendor/           - Third-party (gitignored)"
echo ""
