from __future__ import annotations

import argparse
import json
import sys
from typing import Any

import httpx


def fetch_object_info(base_url: str, timeout_s: float = 5.0) -> dict[str, Any]:
    url = base_url.rstrip("/") + "/object_info"
    with httpx.Client(timeout=timeout_s) as client:
        r = client.get(url)
        r.raise_for_status()
        data = r.json()
        if not isinstance(data, dict):
            raise RuntimeError(f"Unexpected object_info type: {type(data)}")
        return data


def main() -> int:
    parser = argparse.ArgumentParser(description="Check ComfyUI API connectivity")
    parser.add_argument(
        "--base-url",
        default="http://127.0.0.1:8188",
        help="ComfyUI base URL (default: http://127.0.0.1:8188)",
    )
    parser.add_argument("--timeout", type=float, default=5.0, help="Request timeout seconds")
    parser.add_argument("--pretty", action="store_true", help="Pretty print JSON")
    args = parser.parse_args()

    try:
        data = fetch_object_info(args.base_url, timeout_s=args.timeout)
        out = json.dumps(data, ensure_ascii=False, indent=2 if args.pretty else None)
        sys.stdout.write(out + "\n")
        return 0
    except Exception as e:
        sys.stderr.write(f"[check_comfy] ERROR: {e}\n")
        return 2


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