#!/usr/bin/env python3
"""Compare wrapper output with an exact expected-results manifest."""

from __future__ import annotations

import argparse
import csv
from pathlib import Path


FIELDS = ("route", "player_id", "round", "game_1", "game_2", "game_3", "game_4")


def read_rows(path: Path) -> dict[str, dict[str, str]]:
    with path.open(newline="") as handle:
        return {row["file_id"]: row for row in csv.DictReader(handle)}


def normalized(row: dict[str, str]) -> dict[str, str]:
    result = row.copy()
    if "player_id" not in result:
        result["player_id"] = "".join(result.get(f"player_id_{n}", "") for n in (1, 2, 3))
    if "round" not in result:
        result["round"] = str(int(result.get("round_tens") or 0) * 10 + int(result.get("round_ones") or 0))
    return result


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("actual", type=Path)
    parser.add_argument("expected", type=Path)
    args = parser.parse_args()
    actual, expected = read_rows(args.actual), read_rows(args.expected)
    failures: list[str] = []
    for file_id, expected_row in expected.items():
        actual_row = normalized(actual.get(file_id, {}))
        for field in FIELDS:
            if actual_row.get(field, "") != expected_row.get(field, ""):
                failures.append(
                    f"{file_id} {field}: expected {expected_row.get(field, '')!r}, "
                    f"got {actual_row.get(field, '')!r}"
                )
    failures.extend(f"unexpected result: {file_id}" for file_id in sorted(actual.keys() - expected.keys()))
    if failures:
        print("FAIL: batch regression")
        for failure in failures:
            print(f"- {failure}")
        return 1
    print(f"PASS: {len(expected)} exact sheets; accepted/manual-review routing exact")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
