import os
import re
import shutil
import subprocess
import time
from pathlib import Path

DEFAULT_INSTANCE_NAME = "mipilot"
REMOTE_CONTROL_URL = "https://antigravity.google.com"


def find_agy_bin() -> str | None:
    """Vyhledá spustitelný soubor `agy` v PATH nebo ve standardní cestě."""
    bin_path = shutil.which("agy")
    if bin_path:
        return bin_path
    standard_path = Path("/home/agent/.local/bin/agy")
    if standard_path.is_file() and os.access(standard_path, os.X_OK):
        return str(standard_path)
    return None


def get_remote_control_status() -> dict:
    """Získá aktuální stav daemona Remote Control z `agy remote-control status`."""
    agy_bin = find_agy_bin()
    if not agy_bin:
        return {
            "available": False,
            "active": False,
            "instance_name": None,
            "pid": None,
            "url": REMOTE_CONTROL_URL,
            "raw_output": "CLI nástroj agy není nainstalován.",
        }

    try:
        proc = subprocess.run(
            [agy_bin, "remote-control", "status"],
            capture_output=True,
            text=True,
            timeout=15,
        )
        output = (proc.stdout + "\n" + proc.stderr).strip()

        active = "status: active" in output.lower()

        m_inst = re.search(r"Instance name:\s*([^\s(]+)", output)
        instance_name = m_inst.group(1) if m_inst else None

        m_pid = re.search(r"PID\s+(\d+)", output)
        pid = int(m_pid.group(1)) if m_pid else None

        return {
            "available": True,
            "active": active,
            "instance_name": instance_name,
            "pid": pid,
            "url": REMOTE_CONTROL_URL,
            "raw_output": output,
        }
    except Exception as e:
        return {
            "available": True,
            "active": False,
            "instance_name": None,
            "pid": None,
            "url": REMOTE_CONTROL_URL,
            "raw_output": f"Chyba při zjišťování stavu: {e}",
        }


def start_remote_control(name: str | None = None) -> tuple[bool, str]:
    """Zaregistruje a spustí persistentní Remote Control daemon."""
    agy_bin = find_agy_bin()
    if not agy_bin:
        return False, "CLI nástroj `agy` není nainstalován."

    cmd = [agy_bin, "remote-control", "start"]
    instance_name = name or DEFAULT_INSTANCE_NAME
    if instance_name:
        cmd.extend(["--name", instance_name])

    try:
        proc = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=30,
        )
        output = (proc.stdout + "\n" + proc.stderr).strip()
        success = proc.returncode == 0
        return success, output
    except Exception as e:
        return False, f"Chyba při spouštění daemonu: {e}"


def stop_remote_control() -> tuple[bool, str]:
    """Zastaví Remote Control daemon."""
    agy_bin = find_agy_bin()
    if not agy_bin:
        return False, "CLI nástroj `agy` není nainstalován."

    try:
        proc = subprocess.run(
            [agy_bin, "remote-control", "stop"],
            capture_output=True,
            text=True,
            timeout=30,
        )
        output = (proc.stdout + "\n" + proc.stderr).strip()
        return proc.returncode == 0, output
    except Exception as e:
        return False, f"Chyba při zastavování daemonu: {e}"


def restart_remote_control(name: str | None = None) -> tuple[bool, str]:
    """Restartuje Remote Control daemon."""
    stop_remote_control()
    time.sleep(0.5)
    return start_remote_control(name)


def ensure_remote_control(name: str | None = None) -> tuple[bool, str]:
    """Zajistí, že Remote Control daemon neustále běží (pokud je vypnutý, nastartuje ho)."""
    agy_bin = find_agy_bin()
    if not agy_bin:
        return False, "CLI nástroj `agy` není nainstalován."

    status = get_remote_control_status()
    if status.get("active"):
        inst = status.get("instance_name") or name or DEFAULT_INSTANCE_NAME
        return True, f"Remote Control je již aktivní (instance: {inst}, PID: {status.get('pid')})."

    return start_remote_control(name)
