"""Run the forty handwritten RC2 scanner/phone regression cases."""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path


BUNDLE = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(BUNDLE / "wrapper"))
from tdc_omr_wrapper import process  # noqa: E402


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser()
    parser.add_argument("--omrchecker", type=Path, required=True)
    return parser.parse_args()


def expected_answers(form_id: str, questions: int, choices: str) -> dict[str, str]:
    answers = {f"q{i}": choices[(i - 1) % len(choices)] for i in range(1, questions + 1)}
    if form_id.startswith("TDC41-"):
        answers["q31"] = "BC"
        answers["q41"] = ""
    if form_id.startswith("Ohio-"):
        answers["q13"] = "AB"
    if form_id.startswith("Missouri-"):
        answers["q29"] = "AB"
    return answers


def main() -> int:
    args = parse_args()
    cases = json.loads((Path(__file__).with_name("expected_results.json")).read_text())
    counts = {"accepted": 0, "review": 0, "rescan": 0}
    for case in cases:
        result = process(
            Path(__file__).with_name("images") / case["filename"],
            case["form_id"],
            BUNDLE,
            args.omrchecker.resolve(),
        )
        expected = expected_answers(case["form_id"], case["questions"], case["choices"])
        assert result["status"] == case["status"], (case, result)
        assert result["driver_id"] == case["driver_id"], (case, result)
        assert result["answers"] == expected, (case, result)
        counts[result["status"]] += 1
        print(f"PASS: {case['filename']} -> {result['status']}, ID {result['driver_id']}, exact answers")
    assert counts == {"accepted": 22, "review": 18, "rescan": 0}, counts
    print("PASS: all 40 real scans; 22 accepted, 18 review, 0 rescan; exact IDs and answers")
    return 0


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