"""
Django management command to set up the development environment.

This command performs all the setup tasks that the dev_server.sh script does,
allowing the project to run without requiring the shell script.
"""

import subprocess
from pathlib import Path

from django.conf import settings
from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = "Set up the development environment"

    def add_arguments(self, parser):
        parser.add_argument(
            "--skip-migrations",
            action="store_true",
            help="Skip running database migrations",
        )
        parser.add_argument(
            "--skip-static",
            action="store_true",
            help="Skip collecting static files",
        )
        parser.add_argument(
            "--skip-tailwind",
            action="store_true",
            help="Skip building Tailwind CSS",
        )
        parser.add_argument(
            "--skip-superuser",
            action="store_true",
            help="Skip creating development superuser",
        )

    def handle(self, *args, **options):
        """Run the development setup process."""
        self.stdout.write(self.style.SUCCESS("🚀 Setting up ThrillWiki Development Environment..."))

        # Create necessary directories
        self.create_directories()

        # Run database migrations if needed
        if not options["skip_migrations"]:
            self.run_migrations()

        # Seed sample data
        self.seed_sample_data()

        # Create superuser if it doesn't exist
        if not options["skip_superuser"]:
            self.create_superuser()

        # Collect static files
        if not options["skip_static"]:
            self.collect_static()

        # Build Tailwind CSS
        if not options["skip_tailwind"]:
            self.build_tailwind()

        # Run system checks
        self.run_system_checks()

        # Display environment info
        self.display_environment_info()

        self.stdout.write(self.style.SUCCESS("✅ Development environment setup complete!"))

    def create_directories(self):
        """Create necessary directories."""
        self.stdout.write("📁 Creating necessary directories...")
        directories = ["logs", "profiles", "media", "staticfiles", "static/css"]

        for directory in directories:
            dir_path = Path(settings.BASE_DIR) / directory
            dir_path.mkdir(parents=True, exist_ok=True)

        self.stdout.write(self.style.SUCCESS("✅ Directories created"))

    def run_migrations(self):
        """Run database migrations if needed."""
        self.stdout.write("🗄️  Checking database migrations...")

        try:
            # Check if migrations are up to date
            result = subprocess.run(
                ["uv", "run", "manage.py", "migrate", "--check"],
                capture_output=True,
                text=True,
            )

            if result.returncode == 0:
                self.stdout.write(self.style.SUCCESS("✅ Database migrations are up to date"))
            else:
                self.stdout.write("🔄 Running database migrations...")
                subprocess.run(["uv", "run", "manage.py", "migrate", "--noinput"], check=True)
                self.stdout.write(self.style.SUCCESS("✅ Database migrations completed"))

        except subprocess.CalledProcessError as e:
            self.stdout.write(self.style.WARNING(f"⚠️  Migration error (continuing): {e}"))

    def seed_sample_data(self):
        """Seed sample data to the database."""
        self.stdout.write("🌱 Seeding sample data...")

        try:
            subprocess.run(["uv", "run", "manage.py", "seed_sample_data"], check=True)
            self.stdout.write(self.style.SUCCESS("✅ Sample data seeded"))
        except subprocess.CalledProcessError:
            self.stdout.write(self.style.WARNING("⚠️  Could not seed sample data (continuing)"))

    def create_superuser(self):
        """Create development superuser if it doesn't exist."""
        self.stdout.write("👤 Checking for superuser...")

        try:
            from django.contrib.auth import get_user_model

            User = get_user_model()

            if User.objects.filter(is_superuser=True).exists():
                self.stdout.write(self.style.SUCCESS("✅ Superuser already exists"))
            else:
                self.stdout.write("👤 Creating development superuser (admin/admin)...")
                if not User.objects.filter(username="admin").exists():
                    User.objects.create_superuser("admin", "admin@example.com", "admin")
                    self.stdout.write(self.style.SUCCESS("✅ Created superuser: admin/admin"))
                else:
                    self.stdout.write(self.style.SUCCESS("✅ Admin user already exists"))

        except Exception as e:
            self.stdout.write(self.style.WARNING(f"⚠️  Could not create superuser: {e}"))

    def collect_static(self):
        """Collect static files for development."""
        self.stdout.write("📦 Collecting static files...")

        try:
            subprocess.run(
                ["uv", "run", "manage.py", "collectstatic", "--noinput", "--clear"],
                check=True,
            )
            self.stdout.write(self.style.SUCCESS("✅ Static files collected"))
        except subprocess.CalledProcessError as e:
            self.stdout.write(self.style.WARNING(f"⚠️  Could not collect static files: {e}"))

    def build_tailwind(self):
        """Build Tailwind CSS if npm is available."""
        self.stdout.write("🎨 Building Tailwind CSS...")

        try:
            # Check if npm is available
            subprocess.run(["npm", "--version"], capture_output=True, check=True)

            # Build Tailwind CSS
            subprocess.run(["uv", "run", "manage.py", "tailwind", "build"], check=True)
            self.stdout.write(self.style.SUCCESS("✅ Tailwind CSS built"))

        except (subprocess.CalledProcessError, FileNotFoundError):
            self.stdout.write(self.style.WARNING("⚠️  npm not found or Tailwind build failed, skipping"))

    def run_system_checks(self):
        """Run Django system checks."""
        self.stdout.write("🔍 Running system checks...")

        try:
            subprocess.run(["uv", "run", "manage.py", "check"], check=True)
            self.stdout.write(self.style.SUCCESS("✅ System checks passed"))
        except subprocess.CalledProcessError:
            self.stdout.write(self.style.WARNING("❌ System checks failed, but continuing..."))

    def display_environment_info(self):
        """Display development environment information."""
        self.stdout.write("")
        self.stdout.write(self.style.SUCCESS("🌍 Development Environment:"))
        self.stdout.write(f"  - Settings Module: {settings.SETTINGS_MODULE}")
        self.stdout.write(f"  - Debug Mode: {settings.DEBUG}")
        self.stdout.write("  - Database: PostgreSQL with PostGIS")
        self.stdout.write("  - Cache: Local memory cache")
        self.stdout.write("  - Admin URL: http://localhost:8000/admin/")
        self.stdout.write("  - Admin User: admin / admin")
        self.stdout.write("  - Silk Profiler: http://localhost:8000/silk/")
        self.stdout.write("  - Debug Toolbar: Available on debug pages")
        self.stdout.write("  - API Documentation: http://localhost:8000/api/docs/")
        self.stdout.write("")
        self.stdout.write("🌟 Ready to start development server with:")
        self.stdout.write("   uv run manage.py runserver_plus")
        self.stdout.write("")
