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

# Import existing scripts as modules
from django_core_micha.scripts import generate_env, sync_secrets

def run_command(command, cwd=None, ignore_errors=False, shell=False):
    """Helper function to execute shell commands."""
    print(f"[INFO] Running: {' '.join(command) if isinstance(command, list) else command}")
    try:
        # Windows often requires shell=True for Compose commands using env vars
        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()

    # Set logic flags
    sync_local = args.local or args.all
    sync_github = args.all
    env_mode = "edge" if args.edge else "local"
    
    # Determine Compose files
    # Always include base file, then append specific environment file
    compose_files_args = ["-f", "docker-compose.yml"]
    
    if args.edge:
        # Edge Modus: Spezifische Edge-Konfiguration
        edge_file = "docker-compose.edge.yml"
        if Path(edge_file).exists():
             compose_files_args.extend(["-f", edge_file])
        else:
             print(f"[WARN] {edge_file} für Edge-Mode nicht gefunden.")

    elif args.local:
        # Local Modus: Priorisierung von local > override
        local_file = "docker-compose.local.yml"
        override_file = "docker-compose.override.yml"
        
        if Path(local_file).exists():
            print(f"[INFO] Nutze lokale Konfiguration: {local_file}")
            compose_files_args.extend(["-f", local_file])
        elif Path(override_file).exists():
            print(f"[INFO] {local_file} nicht gefunden. Falle zurück auf: {override_file}")
            compose_files_args.extend(["-f", override_file])
        else:
            print("[WARN] Weder .local.yml noch .override.yml gefunden. Starte nur Basis-Konfiguration.")
    
    # Debug-Ausgabe der genutzten Dateien
    print(f"[INFO] Genutzte Compose-Dateien: {' '.join(compose_files_args)}")

    # --- 1. Secrets Sync ---
    if sync_local:
        print("[INFO] Syncing local secrets (.env.local)...")
        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...")
    run_command(["docker", "rm", "-f", "traefik"], ignore_errors=True)
    
    # Cleanup using the specific compose files for this environment
    # KORREKTUR: compose_files -> compose_files_args
    cleanup_cmd = ["docker-compose"] + compose_files_args + ["rm", "-s", "-f", "-v", "backend", "celery_worker"]
    run_command(cleanup_cmd, ignore_errors=True)

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

    # --- 6. Up ---
    print("[INFO] Starting containers...")
    # Detached mode allows the terminal to remain free for the frontend command
    # KORREKTUR: compose_files -> compose_files_args
    up_cmd = ["docker-compose"] + compose_files_args + ["up", "-d", "--remove-orphans"]
    run_command(up_cmd)
    
    print(f"\n[SUCCESS] Backend is running.")
    print(f"To start the frontend with Hot Reloading, open a new terminal in ./frontend and run:")
    print(f"  pnpm install && pnpm dev")

if __name__ == "__main__":
    main()