"""
Django management command to run the development server.

This command automatically sets up the development environment and starts
the server, replacing the need for the dev_server.sh script.
"""

from django.core.management import execute_from_command_line
from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = "Run the development server with automatic setup"

    def add_arguments(self, parser):
        parser.add_argument(
            "--port",
            type=str,
            default="8000",
            help="Port to run the server on (default: 8000)",
        )
        parser.add_argument(
            "--host",
            type=str,
            default="0.0.0.0",
            help="Host to bind the server to (default: 0.0.0.0)",
        )
        parser.add_argument(
            "--skip-setup",
            action="store_true",
            help="Skip the development setup and go straight to running the server",
        )
        parser.add_argument(
            "--use-runserver-plus",
            action="store_true",
            help="Use runserver_plus if available (from django-extensions)",
        )

    def handle(self, *args, **options):
        """Run the development setup and start the server."""
        if not options["skip_setup"]:
            self.stdout.write(self.style.SUCCESS("🚀 Setting up and starting ThrillWiki Development Server..."))

            # Run the setup_dev command first
            execute_from_command_line(["manage.py", "setup_dev"])

        else:
            self.stdout.write(self.style.SUCCESS("🚀 Starting ThrillWiki Development Server..."))

        # Determine which server command to use
        self.get_server_command(options)

        # Start the server
        self.stdout.write("")
        self.stdout.write(
            self.style.SUCCESS(f"🌟 Starting Django development server on http://{options['host']}:{options['port']}")
        )
        self.stdout.write("Press Ctrl+C to stop the server")
        self.stdout.write("")

        try:
            if options["use_runserver_plus"] or self.has_runserver_plus():
                execute_from_command_line(
                    [
                        "manage.py",
                        "runserver_plus",
                        f"{options['host']}:{options['port']}",
                    ]
                )
            else:
                execute_from_command_line(["manage.py", "runserver", f"{options['host']}:{options['port']}"])
        except KeyboardInterrupt:
            self.stdout.write("")
            self.stdout.write(self.style.SUCCESS("👋 Development server stopped"))

    def get_server_command(self, options):
        """Determine which server command to use."""
        if options["use_runserver_plus"] or self.has_runserver_plus():
            return "runserver_plus"
        return "runserver"

    def has_runserver_plus(self):
        """Check if runserver_plus is available (django-extensions)."""
        try:
            import django_extensions  # noqa: F401

            return True
        except ImportError:
            return False
