#!/usr/bin/env python3
"""
Review watch-only Agent candidates for possible priority upgrade.

This command is read-only. It does not approve registry promotion, market
scorecard updates, replay, SDK installation, paid API use, shadow/canary, or
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_watch_promotion_review.py"


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

    service = _load_service()
    report = service.run_agent_market_watch_promotion_review(
        watch_report=_read_json(Path(args.watch_report)),
        integration_review=_read_json(Path(args.integration_review)),
        discovery_classification=_read_json(Path(args.discovery_classification)),
        candidate_registry=_read_json(Path(args.candidates)),
    )
    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_watch_promotion_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 watch promotion 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())
