from __future__ import annotations

import argparse
import json
import shutil
import time
from pathlib import Path

import requests

INSTALL_HINTS = {
    "claude_code": "Install Claude Code CLI and ensure `claude` is in PATH.",
    "hermes": "Install Hermes CLI and ensure `hermes` is in PATH.",
    "openclaw": "Install OpenClaw CLI and ensure `openclaw` is in PATH.",
}


def command_status(cmd: str) -> dict:
    path = shutil.which(cmd)
    return {
        "command": cmd,
        "installed": bool(path),
        "path": path or "",
        "hint": "",
    }


def check_api(base_url: str, api_key: str, model: str) -> dict:
    url = f"{base_url.rstrip('/')}/chat/completions"
    headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
    payload = {
        "model": model,
        "messages": [{"role": "user", "content": "回复ok"}],
        "stream": False,
    }
    started = time.time()
    try:
        resp = requests.post(url, headers=headers, json=payload, timeout=25)
        elapsed_ms = int((time.time() - started) * 1000)
        ok = resp.status_code == 200
        preview = resp.text[:240]
        return {
            "ok": ok,
            "status_code": resp.status_code,
            "elapsed_ms": elapsed_ms,
            "preview": preview,
        }
    except Exception as exc:  # noqa: BLE001
        return {"ok": False, "status_code": 0, "elapsed_ms": -1, "preview": str(exc)}


def main() -> int:
    parser = argparse.ArgumentParser(description="Check client OOTB readiness for Fleet + executors")
    parser.add_argument("--base-url", default="https://agent-fleet.cn/v1", help="Fleet OpenAI-compatible base URL")
    parser.add_argument("--api-key", default="sk-af-public-test", help="Fleet API key")
    parser.add_argument("--model", default="fleet-auto", help="Model used for quick health check")
    parser.add_argument("--config", default="", help="Optional customer config json path")
    parser.add_argument("--out", default="dist/fleet-desktop-bundle-v1/ootb_check_report.json", help="Output JSON path")
    args = parser.parse_args()

    if args.config:
        cfg_path = Path(args.config)
        if cfg_path.exists():
            cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
            args.base_url = str(cfg.get("fleet_base_url") or args.base_url)
            args.api_key = str(cfg.get("fleet_api_key") or args.api_key)
            args.model = str(cfg.get("default_model") or args.model)

    checks = {
        "fleet_api": check_api(args.base_url, args.api_key, args.model),
        "executors": {
            "claude_code": command_status("claude"),
            "hermes": command_status("hermes"),
            "openclaw": command_status("openclaw"),
        },
    }
    for key, val in checks["executors"].items():
        if not val["installed"]:
            val["hint"] = INSTALL_HINTS.get(key, "Install required executor CLI.")
    all_ok = checks["fleet_api"]["ok"] and all(v["installed"] for v in checks["executors"].values())
    report = {"ok": all_ok, "checks": checks}

    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    out.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
    print(f"ootb_ok={all_ok}")
    print(f"report={out.resolve()}")
    return 0 if all_ok else 1


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