import os
import subprocess
from pathlib import Path
from .config import detect_host_repos_path


def deploy_preview(
    repo_name: str,
    branch: str,
    host_repos_path: str,
    preview_domain: str,
    repos_base_dir: Path | None = None
) -> str:
    """Spustí živý náhled (Preview Environment) připojený do Coolify sítě pro Traefik routing."""
    safe_branch = branch.replace("/", "-").replace("_", "-").lower()
    container_name = f"mipilot-preview-{repo_name}-{safe_branch}"[:60]
    host = f"{repo_name}-{safe_branch}.{preview_domain}"

    # Zajistíme správnou cestu na hostiteli i při nesprávném/výchozím fallbacku
    real_host_repos = detect_host_repos_path(fallback=host_repos_path)
    host_repo_dir = f"{real_host_repos}/{repo_name}"

    base_dir = repos_base_dir or Path("/home/agent/repos")
    local_repo_dir = base_dir / repo_name

    workdir = "/app"
    port = 3000

    # 1. Kontrola konfigurace .mipilot.yml v repozitáři
    custom_cmd = None
    mipilot_yaml = local_repo_dir / ".mipilot.yml"
    if mipilot_yaml.exists():
        try:
            for line in mipilot_yaml.read_text(encoding="utf-8").splitlines():
                if ":" in line:
                    k, v = line.split(":", 1)
                    k, v = k.strip(), v.strip()
                    if k == "cmd":
                        custom_cmd = v
                    elif k == "port":
                        port = int(v)
                    elif k == "dir":
                        workdir = f"/app/{v.strip('/')}"
        except Exception:
            pass

    # 2. Automatická detekce podsložky webové aplikace (pokud package.json není v kořeni)
    if not custom_cmd and not (local_repo_dir / "package.json").exists():
        for sub in ("frontend", "web", "client", "ui", "app"):
            if (local_repo_dir / sub / "package.json").exists():
                workdir = f"/app/{sub}"
                break

    subprocess.run(["docker", "rm", "-f", container_name], capture_output=True)

    # 3. Příkaz pro start aplikace
    if custom_cmd:
        start_cmd = custom_cmd
    else:
        start_cmd = (
            f"if [ -f package.json ]; then "
            f"[ -d node_modules ] || npm install; "
            f"for cfg in vite.config.js vite.config.ts vite.config.mjs; do "
            f"if [ -f \"$cfg\" ] && ! grep -q \"allowedHosts\" \"$cfg\"; then "
            f"sed -i 's/server:[[:space:]]*{{/server: {{ allowedHosts: true,/g' \"$cfg\"; "
            f"fi; done; "
            f"npm run dev -- --host 0.0.0.0 --port {port} || npm start || npx serve -s -l {port} .; "
            f"elif [ -f index.html ] || [ -d dist ] || [ -d public ]; then "
            f"npx serve -s -l {port} .; "
            f"else "
            f"echo '<!DOCTYPE html><html><head><meta charset=\"utf-8\"><title>mipilot preview</title>"
            f"<style>body{{font-family:sans-serif;padding:40px;background:#111;color:#eee}}h1{{color:#4af}}</style></head>"
            f"<body><h1>mipilot Live Preview</h1><p>Repozitář <b>{repo_name}</b> neobsahuje webový frontend.</p></body></html>' > /tmp/index.html && "
            f"npx serve -s -l {port} /tmp; "
            f"fi"
        )

    docker_cmd = [
        "docker", "run", "-d",
        "--name", container_name,
        "--network", "coolify",
        "--memory", "1g",
        "-e", f"PORT={port}",
        "-e", "HOST=0.0.0.0",
        "-v", f"{host_repo_dir}:/app",
        "-w", workdir,
        "-l", "traefik.enable=true",
        "-l", f"traefik.http.routers.{container_name}.rule=Host(`{host}`)",
        "-l", f"traefik.http.routers.{container_name}.entrypoints=https",
        "-l", f"traefik.http.routers.{container_name}.tls=true",
        "-l", f"traefik.http.routers.{container_name}.tls.certresolver=letsencrypt",
        "-l", f"traefik.http.services.{container_name}.loadbalancer.server.port={port}",
        "node:22-alpine",
        "sh", "-c", start_cmd
    ]
    proc = subprocess.run(docker_cmd, capture_output=True, text=True)
    if proc.returncode != 0:
        raise RuntimeError(f"Chyba při spuštění preview kontejneru: {proc.stderr}")

    return f"https://{host}"


def list_previews() -> str:
    proc = subprocess.run(
        ["docker", "ps", "--filter", "name=mipilot-preview-", "--format", "{{.Names}} ({{.Status}})"],
        capture_output=True, text=True
    )
    return proc.stdout.strip() or "Žádné běžící preview kontejnery."


def stop_preview(name: str) -> str:
    if not name.startswith("mipilot-preview-"):
        name = f"mipilot-preview-{name}"
    proc = subprocess.run(["docker", "rm", "-f", name], capture_output=True, text=True)
    return f"Preview `{name}` zastaveno." if proc.returncode == 0 else f"Chyba: {proc.stderr}"
