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

import os
import sys


def main():
    """Run administrative tasks."""
    # Auto-detect environment based on command line arguments and environment variables
    settings_module = detect_settings_module()
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", settings_module)

    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        print(
            "Error: Couldn't import Django. Make sure Django is installed and "
            "available on your PYTHONPATH environment variable. "
            "Did you forget to activate a virtual environment?"
        )
        print("\nTo set up your development environment, try:")
        print("  uv run manage.py setup_dev")
        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

    execute_from_command_line(sys.argv)


def detect_settings_module():
    """
    Auto-detect the appropriate settings module based on context.

    Detection order:
    1. DJANGO_SETTINGS_MODULE environment variable (explicit override)
    2. Test command detection (uses test settings)
    3. Production indicators (environment variables from cloud providers)
    4. Staging indicators (staging-specific environment variables)
    5. DEBUG environment variable (False = production)
    6. Default to local development

    Returns:
        str: The settings module path (e.g., "config.django.local")
    """
    # Check if DJANGO_SETTINGS_MODULE is already set
    if "DJANGO_SETTINGS_MODULE" in os.environ:
        return os.environ["DJANGO_SETTINGS_MODULE"]

    # Test environment detection
    if "test" in sys.argv:
        if "accounts" in sys.argv:
            return "config.django.test_accounts"
        return "config.django.test"

    # Production indicators from various cloud providers
    production_indicators = [
        "DYNO",  # Heroku
        "AWS_EXECUTION_ENV",  # AWS Lambda
        "AWS_ECS_CLUSTER",  # AWS ECS
        "KUBERNETES_SERVICE_HOST",  # Kubernetes
        "DOCKER_CONTAINER",  # Docker
        "FLY_APP_NAME",  # Fly.io
        "RAILWAY_ENVIRONMENT",  # Railway
        "RENDER",  # Render
        "VERCEL",  # Vercel
    ]

    if any(indicator in os.environ for indicator in production_indicators):
        return "config.django.production"

    # Staging detection (explicit staging environment variable)
    if os.environ.get("ENVIRONMENT", "").lower() in ("staging", "stage"):
        return "config.django.production"  # Use production settings for staging

    # Check DEBUG environment variable
    debug = os.environ.get("DEBUG", "").lower()
    if debug in ("false", "0", "no", "off"):
        return "config.django.production"

    # Default to local development
    return "config.django.local"


if __name__ == "__main__":
    main()
