from __future__ import annotations

from crowley_diary.util import load_json, project_root


def test_poc_failure_rules_are_explicit_in_transcription_specification() -> None:
    prompt = (project_root() / "prompts" / "transcribe-page.md").read_text(
        encoding="utf-8"
    )
    for literal in (
        "Literal source date",
        "nice-pleasant",
        "Incomplete-looking material without survival continuity",
        "Low-confidence handwriting",
        "Cross-page cancellation is not logical continuation",
        "ditto marks",
        "fractions",
        "confidence: unreadable",
    ):
        assert literal in prompt


def test_owner_approved_page232_begins_sleep_and_retains_handwriting_uncertainty() -> None:
    page = load_json(project_root() / "edition" / "owner-approved" / "page-232.json")
    matching = []

    def walk(node: object) -> None:
        if isinstance(node, dict):
            if node.get("type") == "unclear" and "little one" in (node.get("reading") or ""):
                matching.append(node)
            for value in node.values():
                walk(value)
        elif isinstance(node, list):
            for value in node:
                walk(value)

    walk(page["blocks"])
    assert len(matching) == 1
    assert matching[0]["reading"] == "Sleep my little one sleep"
    assert matching[0]["alternatives"] == ["Sleep my little one asleep"]
    assert matching[0]["confidence"] == "low"


def test_incomplete_material_does_not_assert_surviving_page_continuation() -> None:
    page = load_json(project_root() / "evaluation" / "goldens" / "page-116.json")
    assert page["boundary"]["ends_mid_block"] == "uncertain"
    assert page["blocks"][-1]["continuation"]["to_next"] == "no"


def test_low_confidence_handwriting_retains_alternatives() -> None:
    page = load_json(project_root() / "evaluation" / "goldens" / "page-232.json")
    unclear = []

    def walk(node: object) -> None:
        if isinstance(node, dict):
            if node.get("type") == "unclear":
                unclear.append(node)
            for value in node.values():
                walk(value)
        elif isinstance(node, list):
            for value in node:
                walk(value)

    walk(page["blocks"])
    assert any(node["confidence"] == "low" and len(node["alternatives"]) >= 2 for node in unclear)


def test_cross_page_cancellation_does_not_link_closed_entry() -> None:
    page = load_json(project_root() / "evaluation" / "goldens" / "page-288.json")
    thursday = next(
        block
        for block in page["blocks"]
        if (block.get("date") or {}).get("date_source") == "Thursday Oct. 19 - 99"
    )
    assert thursday["continuation"]["to_next"] == "no"
    assert thursday["continuation"]["next"] is None
