#!/usr/bin/env python3
"""
Build an aggregate RCA report for a completed NeMo/Nemotron external replay.

This command is local and deterministic. It reads already-produced reports and
external result JSONL, then writes aggregate JSON only; raw JSONL remains local.
"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path
from typing import Any


ROOT = Path(__file__).resolve().parents[2]
API_SRC = ROOT / "apps" / "api"
sys.path.insert(0, str(API_SRC))

from src.services.agent_nemotron_replay_failure_analysis import (  # noqa: E402
    analyze_nemotron_replay_failure,
)


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Analyze NeMo/Nemotron external replay failure modes."
    )
    parser.add_argument("--external-results", required=True, help="external result JSONL")
    parser.add_argument("--external-runner-report", required=True, help="runner report JSON")
    parser.add_argument("--finalizer-report", required=True, help="finalizer report JSON")
    parser.add_argument("--scorecard", required=True, help="scorecard report JSON")
    parser.add_argument("--output", required=True, help="aggregate failure analysis JSON")
    args = parser.parse_args()

    report = analyze_nemotron_replay_failure(
        external_results=_read_jsonl(Path(args.external_results)),
        external_runner_report=_read_json(Path(args.external_runner_report)),
        finalizer_report=_read_json(Path(args.finalizer_report)),
        scorecard_report=_read_json(Path(args.scorecard)),
        source_reports={
            "external_results": args.external_results,
            "external_runner_report": args.external_runner_report,
            "finalizer_report": args.finalizer_report,
            "scorecard": args.scorecard,
        },
    )
    Path(args.output).write_text(
        json.dumps(report, ensure_ascii=False, indent=2, sort_keys=True) + "\n",
        encoding="utf-8",
    )
    print(json.dumps(report, ensure_ascii=False, sort_keys=True))
    return 0 if report["decision"] == "approved" else 2


def _read_json(path: Path) -> dict[str, Any]:
    with path.open(encoding="utf-8") as handle:
        return json.load(handle)


def _read_jsonl(path: Path) -> list[dict[str, Any]]:
    records: list[dict[str, Any]] = []
    with path.open(encoding="utf-8") as handle:
        for line_number, line in enumerate(handle, start=1):
            line = line.strip()
            if not line or line.startswith("#"):
                continue
            try:
                records.append(json.loads(line))
            except Exception as exc:
                raise SystemExit(f"{path}:{line_number}: invalid JSONL: {exc}") from exc
    return records


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