"""Launchd service for MLX Manager itself (not MLX servers)."""

import plistlib
import shutil
import subprocess
import sys
from pathlib import Path

from mlx_manager.services.launchctl_utils import bootout, bootstrap

LABEL = "com.mlx-manager.app"


def _find_executable() -> str:
    """Find the mlx-manager executable using stable path resolution.

    Prefers shutil.which() (finds symlinks that survive brew upgrades)
    over sys.executable-relative paths (version-specific Cellar paths).
    """
    which_path = shutil.which("mlx-manager")
    if which_path:
        return which_path

    # Fallback: resolve relative to sys.executable
    candidate = Path(sys.executable).parent / "mlx-manager"
    if candidate.exists():
        return str(candidate)

    # Last resort: use python -m
    return ""


def get_plist_path() -> Path:
    """Get the plist file path."""
    return Path.home() / "Library" / "LaunchAgents" / f"{LABEL}.plist"


def install_manager_service(host: str = "127.0.0.1", port: int = 10242) -> str:
    """Install MLX Manager as a launchd service."""
    launch_agents_dir = Path.home() / "Library" / "LaunchAgents"
    launch_agents_dir.mkdir(parents=True, exist_ok=True)

    mlx_manager_path = _find_executable()

    if mlx_manager_path:
        program_args = [
            mlx_manager_path,
            "serve",
            "--host",
            host,
            "--port",
            str(port),
            "--no-open",
        ]
    else:
        program_args = [
            sys.executable,
            "-m",
            "mlx_manager.cli",
            "serve",
            "--host",
            host,
            "--port",
            str(port),
            "--no-open",
        ]

    # Determine PATH: prefer the directory of the resolved executable
    if mlx_manager_path:
        exe_dir = str(Path(mlx_manager_path).parent)
    else:
        exe_dir = str(Path(sys.executable).parent)

    plist = {
        "Label": LABEL,
        "ProgramArguments": program_args,
        "RunAtLoad": True,
        "KeepAlive": {"SuccessfulExit": False, "Crashed": True},
        "StandardOutPath": f"/tmp/{LABEL}.log",
        "StandardErrorPath": f"/tmp/{LABEL}.err",
        "EnvironmentVariables": {
            "PATH": f"{exe_dir}:/usr/local/bin:/usr/bin:/bin",
            "HOME": str(Path.home()),
            "PYTHONUNBUFFERED": "1",
        },
        "ProcessType": "Interactive",
        "ThrottleInterval": 30,
    }

    plist_path = get_plist_path()

    with open(plist_path, "wb") as f:
        plistlib.dump(plist, f)

    bootstrap(str(plist_path), LABEL)

    return str(plist_path)


def uninstall_manager_service() -> bool:
    """Uninstall the MLX Manager launchd service."""
    plist_path = get_plist_path()

    if not plist_path.exists():
        return False

    bootout(LABEL)
    plist_path.unlink(missing_ok=True)

    return True


def is_service_installed() -> bool:
    """Check if the service is installed."""
    return get_plist_path().exists()


def is_service_running() -> bool:
    """Check if the service is running."""
    result = subprocess.run(["launchctl", "list", LABEL], capture_output=True, text=True)
    return result.returncode == 0
