#!/usr/bin/env python3
"""
Validate a NeMo/Nemotron request pack before an external runner consumes it.

This command is read-only and local. It does not call NIM, NVIDIA APIs,
production tools, or LLMs.
"""

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_preflight import (  # noqa: E402
    evaluate_nemotron_external_runner_preflight,
)


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Preflight NeMo/Nemotron external runner request pack."
    )
    parser.add_argument("--fixtures", required=True, help="internal fixture JSONL")
    parser.add_argument("--inputs", required=True, help="candidate input JSONL")
    parser.add_argument("--requests", required=True, help="NeMo request JSONL")
    parser.add_argument("--output", help="preflight report JSON")
    args = parser.parse_args()

    report = evaluate_nemotron_external_runner_preflight(
        fixtures=_read_jsonl(Path(args.fixtures)),
        candidate_inputs=_read_jsonl(Path(args.inputs)),
        requests=_read_jsonl(Path(args.requests)),
    ).to_dict()
    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)
    return 0 if report["valid"] else 2


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())
