#!/usr/bin/env python3
"""
Build a read-only candidate-intake report from market-watch discovery results.

The command does not edit the candidate registry, install SDKs, call LLMs,
approve paid API use, enter shadow/canary, or mutate production routing.
"""

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_discovery_review.py"


def main() -> int:
    parser = argparse.ArgumentParser(description="Run AWOOOI Agent market discovery review.")
    parser.add_argument("--watch-report", required=True, help="agent_market_watch_report_v1 JSON")
    parser.add_argument(
        "--candidates",
        default="docs/ai/agent-replacement-candidates.v1.json",
        help="candidate registry JSON",
    )
    parser.add_argument(
        "--source-registry",
        default="docs/ai/agent-market-watch-sources.v1.json",
        help="market watch source registry JSON",
    )
    parser.add_argument("--previous-review", help="previous discovery review JSON")
    parser.add_argument("--output", help="review output JSON")
    args = parser.parse_args()

    service = _load_service()
    previous_review = _read_json(Path(args.previous_review)) if args.previous_review else None
    report = service.run_agent_market_discovery_review(
        watch_report=_read_json(Path(args.watch_report)),
        candidate_registry=_read_json(Path(args.candidates)),
        source_registry=_read_json(Path(args.source_registry)),
        previous_review=previous_review,
    )
    rendered = json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True)
    if args.output:
        Path(args.output).write_text(rendered + "\n", encoding="utf-8")
    else:
        print(rendered)
    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_service() -> Any:
    module_name = "awoooi_agent_market_discovery_review_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 discovery review service from {SERVICE_PATH}")
    module = importlib.util.module_from_spec(spec)
    sys.modules[module_name] = module
    spec.loader.exec_module(module)
    return module


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