#!/usr/bin/env python3
"""
Build an operator-reviewable integration decision from an Agent market watch.

The command is read-only. It does not 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_integration_review.py"


def main() -> int:
    parser = argparse.ArgumentParser(description="Run AWOOOI Agent market integration 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(
        "--scorecard",
        default="docs/evaluations/agent_market_capability_scorecard_2026-06-01.json",
        help="market capability scorecard JSON",
    )
    parser.add_argument(
        "--review-scope",
        choices=["changed", "actionable", "all"],
        default="actionable",
        help="changed: changed candidates only; actionable: changed or source-failed; all: periodic full review",
    )
    parser.add_argument("--output", help="review output JSON")
    args = parser.parse_args()

    service = _load_service()
    report = service.run_agent_market_integration_review(
        watch_report=_read_json(Path(args.watch_report)),
        candidate_registry=_read_json(Path(args.candidates)),
        scorecard=_read_json(Path(args.scorecard)),
        review_scope=args.review_scope,
    )
    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_integration_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 integration 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())
