#!/usr/bin/env python3
"""
Build the recurring AI Agent market watch report.

The command is read-only. It fetches primary sources when run in live mode, but
does not call LLMs, install SDKs, create credentials, mutate production, or
approve integration.
"""

from __future__ import annotations

import argparse
import importlib.util
import json
import sys
from pathlib import Path
from typing import Any


ROOT = Path(__file__).resolve().parents[2]
SERVICE_PATH = ROOT / "apps" / "api" / "src" / "services" / "agent_market_watch.py"
run_agent_market_watch = None


def main() -> int:
    global run_agent_market_watch
    if run_agent_market_watch is None:
        run_agent_market_watch = _load_market_watch_service()

    parser = argparse.ArgumentParser(description="Run AWOOOI Agent market watch.")
    parser.add_argument(
        "--registry",
        default="docs/ai/agent-market-watch-sources.v1.json",
        help="market watch source registry JSON",
    )
    parser.add_argument("--output", required=True, help="report output JSON")
    parser.add_argument(
        "--mode",
        choices=("offline", "live"),
        default="live",
        help="offline validates registry only; live fetches primary sources",
    )
    parser.add_argument(
        "--previous-report",
        help="optional previous market watch report for change detection",
    )
    parser.add_argument("--timeout-seconds", type=int, default=12)
    args = parser.parse_args()

    registry_path = Path(args.registry)
    registry = _read_json(registry_path)
    previous = _read_json(Path(args.previous_report)) if args.previous_report else None
    report = run_agent_market_watch(
        registry,
        registry_path=args.registry,
        mode=args.mode,
        previous_report=previous,
        timeout_seconds=args.timeout_seconds,
    )
    Path(args.output).write_text(
        json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
        encoding="utf-8",
    )
    print(json.dumps(report["summary"], ensure_ascii=False, sort_keys=True))
    return 0


def _read_json(path: Path) -> dict[str, Any]:
    with path.open(encoding="utf-8") as handle:
        payload = json.load(handle)
    if not isinstance(payload, dict):
        raise SystemExit(f"{path}: expected JSON object")
    return payload


def _load_market_watch_service() -> Any:
    module_name = "awoooi_agent_market_watch_service"
    spec = importlib.util.spec_from_file_location(module_name, SERVICE_PATH)
    if spec is None or spec.loader is None:
        raise SystemExit(f"cannot load market watch service from {SERVICE_PATH}")
    module = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = module
    spec.loader.exec_module(module)
    return module.run_agent_market_watch


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