#!/usr/bin/env python3
"""
Normalize candidate Agent replay result JSONL into AWOOOI scorecard JSONL.

Usage:
  python scripts/agents/normalize-agent-replay-results.py \
    --input /tmp/nemo-raw-results.jsonl \
    --output /tmp/nemo-candidate-scorecard-input.jsonl
"""

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_replay_normalizer import (  # noqa: E402
    CandidateReplayResult,
    normalize_candidate_result,
)


def main() -> int:
    parser = argparse.ArgumentParser(
        description="Normalize raw candidate replay results into scorecard JSONL."
    )
    parser.add_argument("--input", required=True, help="Candidate raw result JSONL")
    parser.add_argument("--output", required=True, help="Normalized replay JSONL")
    args = parser.parse_args()

    records = []
    for payload in _read_jsonl(Path(args.input)):
        result = CandidateReplayResult.from_dict(payload)
        records.append(normalize_candidate_result(result))

    with Path(args.output).open("w", encoding="utf-8") as handle:
        for record in records:
            handle.write(json.dumps(record.__dict__, ensure_ascii=False, sort_keys=True))
            handle.write("\n")

    print(
        json.dumps(
            {
                "input": args.input,
                "output": args.output,
                "records": len(records),
            },
            ensure_ascii=False,
            sort_keys=True,
        )
    )
    return 0


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