import argparse
import subprocess
import sys
import shutil
import os
from pathlib import Path

# Importiere die existierenden Skripte direkt, um sie als Module aufzurufen
from django_core_micha.scripts import generate_env, sync_secrets

def run_command(command, cwd=None, ignore_errors=False, shell=False):
    """Hilfsfunktion zum Ausführen von Shell-Befehlen mit Logging."""
    print(f"[INFO] Running: {' '.join(command) if isinstance(command, list) else command}")
    try:
        # shell=True nur nutzen, wenn wir komplexe Shell-Features brauchen (versuchen wir zu vermeiden)
        # shell=True ist unter Windows oft nötig für Docker Compose Commands, die Environment-Vars nutzen
        is_windows = sys.platform == "win32"
        use_shell = shell or is_windows
        
        subprocess.run(command, check=True, cwd=cwd, shell=use_shell)
    except subprocess.CalledProcessError as e:
        if ignore_errors:
            print(f"[WARN] Command failed (ignored): {e}")
        else:
            print(f"[ERROR] Command failed: {e}")
            sys.exit(e.returncode)

def main():
    parser = argparse.ArgumentParser(description="Developer Runner for Docker setup")
    parser.add_argument("--local", action="store_true", help="Sync local secrets and run in local mode")
    parser.add_argument("--edge", action="store_true", help="Run in edge mode (uses docker-compose.edge.yml)")
    parser.add_argument("--all", action="store_true", help="Sync ALL secrets (GitHub + Local)")
    
    args = parser.parse_args()

    # Logik-Flags setzen
    sync_local = args.local or args.all
    sync_github = args.all
    env_mode = "edge" if args.edge else "local"
    
    # Compose Flags bestimmen
    compose_files = []
    if args.edge:
        compose_files = ["-f", "docker-compose.edge.yml"]
    
    print(f"[INFO] Running Docker setup in {env_mode} mode...")

    # --- 1. Secrets Sync ---
    if sync_local:
        print("[INFO] Syncing local secrets (.env.local)...")
        # Wir rufen die main() Funktion des anderen Skripts direkt auf
        # Wir simulieren sys.argv Argumente für das aufgerufene Skript
        sys.argv = ["sync-secrets", "--target", "local"]
        sync_secrets.main()

    if sync_github:
        print("[INFO] Syncing GitHub secrets...")
        sys.argv = ["sync-secrets", "--target", "github"]
        sync_secrets.main()

    # --- 2. Generate .env ---
    print(f"[INFO] Generating .env for environment: {env_mode}...")
    sys.argv = ["generate-env", "--env", env_mode]
    generate_env.main()

    # --- 3. Copy .env to frontend ---
    frontend_env_path = Path("frontend/.env")
    if Path("frontend").exists():
        print("[INFO] Copying .env to frontend...")
        shutil.copy(".env", frontend_env_path)
    else:
        print("[WARN] 'frontend' folder not found. Skipping .env copy.")

    # --- 4. Cleanup ---
    print("[INFO] Cleaning up conflicting containers...")
    # Globaler Cleanup (Traefik), falls nötig. ignore_errors=True
    run_command(["docker", "rm", "-f", "traefik"], ignore_errors=True)
    
    # Projekt-spezifischer Cleanup für Hot-Reloading (Backend & Worker)
    # Wir nutzen docker compose rm, um sicherzustellen, dass wir den richtigen Kontext haben
    cleanup_cmd = ["docker-compose"] + compose_files + ["rm", "-s", "-f", "-v", "backend", "celery_worker"]
    run_command(cleanup_cmd, ignore_errors=True)

    # --- 5. Build ---
    print("[INFO] Building containers...")
    build_cmd = ["docker-compose"] + compose_files + ["build"]
    run_command(build_cmd)

    # --- 6. Up ---
    print("[INFO] Starting containers...")
    up_cmd = ["docker-compose"] + compose_files + ["up", "--remove-orphans"]
    run_command(up_cmd)

if __name__ == "__main__":
    main()