#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
    """Run administrative tasks."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc

    # Custom Override: Use Uvicorn with SSL if 'runserver' is called
    if "runserver_uvicorn" in sys.argv:
        try:
            import uvicorn
            from dotenv import load_dotenv
            load_dotenv()
            
            print("\n[*] Starting Uvicorn Server...")
            
            # Simple port/host parsing
            host = "0.0.0.0" 
            port = 8000
            for arg in sys.argv:
                if ":" in arg:
                    try:
                        h, p = arg.split(":")
                        if h: host = h
                        if p: port = int(p)
                    except: pass
                elif arg.isdigit():
                    port = int(arg)
            
            # Get cert paths from environment or use default
            cert_file = os.getenv("CERT_FILE", "")
            key_file = os.getenv("KEY_FILE", "")

            if cert_file and key_file and os.path.exists(cert_file) and os.path.exists(key_file):
                print(f"[SSL] Certificates found at {cert_file}. Enabling SSL.")
                uvicorn.run(
                    "config.asgi:application",
                    host=host,
                    port=port,
                    ssl_certfile=cert_file,
                    ssl_keyfile=key_file,
                    reload=False
                )
            else:
                if cert_file or key_file:
                    print(f"[!] Certificates NOT found or not provided.")
                print(f"[!] Running in HTTP (non-secure) mode.")
                uvicorn.run(
                    "config.asgi:application",
                    host=host,
                    port=port,
                    reload=False
                )
            return
        except ImportError:
            print("[!] Uvicorn not installed. Falling back to standard runserver.")
        except Exception as e:
            print(f"[!] Error starting Uvicorn: {e}")
            print("Falling back to standard runserver.")
    
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()
