from __future__ import annotations

import json
import subprocess
import sys
from pathlib import Path


HERE = Path(__file__).resolve()


def _discover_paths() -> tuple[Path, Path, Path]:
    # Running inside repo: scripts/release/desktop_launcher.py
    repo_root = HERE.parents[2]
    repo_ootb = repo_root / "scripts" / "release" / "check_client_ootb.py"
    if repo_ootb.exists():
        default_config = repo_root / "dist" / "fleet-desktop-bundle-v1" / "config" / "customer.config.json"
        return repo_root, repo_ootb, default_config

    # Running inside bundle: dist/fleet-desktop-bundle-v1/bin/launch.py
    bundle_root = HERE.parents[1]
    bundled_ootb = bundle_root / "bin" / "check_client_ootb.py"
    default_config = bundle_root / "config" / "customer.config.json"
    return bundle_root, bundled_ootb, default_config


def load_config(path: Path) -> dict:
    if not path.exists():
        raise FileNotFoundError(f"config not found: {path}")
    return json.loads(path.read_text(encoding="utf-8"))


def run_ootb(config_path: Path) -> int:
    root, ootb_script, _ = _discover_paths()
    out_path = config_path.parents[1] / "ootb_check_report.json"
    args = [
        sys.executable,
        str(ootb_script),
        "--config",
        str(config_path),
        "--out",
        str(out_path),
    ]
    proc = subprocess.run(args, cwd=str(root))
    if out_path.exists():
        report = json.loads(out_path.read_text(encoding="utf-8"))
        for name, item in (report.get("checks", {}).get("executors", {}) or {}).items():
            if not item.get("installed"):
                print(f"- missing {name}: {item.get('hint')}")
    return int(proc.returncode)


def main() -> int:
    _, _, default_config = _discover_paths()
    config_path = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else default_config
    cfg = load_config(config_path)
    print("Fleet Desktop Launcher")
    print(f"- base_url: {cfg.get('fleet_base_url')}")
    print(f"- model: {cfg.get('default_model')}")
    print("- running ootb checks...")
    code = run_ootb(config_path)
    if code == 0:
        print("OOTB check passed. You can start local executors now.")
    else:
        print("OOTB check failed. See report json for details.")
    return code


if __name__ == "__main__":
    raise SystemExit(main())
