from __future__ import annotations

from dataclasses import dataclass
from typing import Any

from .fixtures import FixtureRecord

# Predicted response_payload pages -> the key review.json nests that page's
# human-corrected entries under.
PAGE_TO_TRUTH_KEY = {
    "left_page": "left_page_data",
    "right_page": "right_page_data",
    "coagulation": "coagulation_data",
}


@dataclass(frozen=True)
class GroundTruth:
    source: str  # "review" | "none"
    log_date: str | None
    page_data: dict[str, dict[str, list[dict[str, Any]]]]  # page -> {table: [rows]}


def extract_ground_truth(record: FixtureRecord) -> GroundTruth:
    """Extract flat, human-verified ground truth from a fixture record.

    `expected/response_payload.json` is only the *previous OCR run* -- not a verified
    answer -- so it's never used as ground truth here. Only a submitted/worked
    `expected/review.json` counts; its absence means this record can't be scored.
    """
    if record.review is None:
        return GroundTruth(source="none", log_date=record.log_date, page_data={})

    page_data = {
        page_key: record.review[truth_key]
        for page_key, truth_key in PAGE_TO_TRUTH_KEY.items()
        if truth_key in record.review
    }

    return GroundTruth(source="review", log_date=record.log_date, page_data=page_data)
