from __future__ import annotations

from crowley_diary.render import render_lines, render_page
from crowley_diary.util import load_json, project_root


def line(number: int, text: str, line_end: str) -> dict:
    return {
        "line_number": number,
        "segments": [{"type": "text", "text": text}],
        "line_end": line_end,
    }


def test_word_break_hyphen_is_diplomatic_but_not_reading_text() -> None:
    lines = [line(1, "prepara", "hyphen_word_break"), line(2, "tory", "block_end")]
    assert render_lines(lines, diplomatic=True) == "prepara-\ntory"
    assert render_lines(lines, diplomatic=False) == "preparatory"


def test_lexical_hyphen_survives_reading_text() -> None:
    lines = [line(1, "good", "hyphen_lexical"), line(2, "night", "block_end")]
    assert render_lines(lines, diplomatic=False) == "good-night"


def test_internal_source_hyphen_is_not_normalized_away() -> None:
    page = load_json(project_root() / "evaluation" / "goldens" / "page-006.json")
    assert "nice-pleasant" in render_page(page)


def test_small_marks_ditto_marks_and_fractions_survive_rendering() -> None:
    page = load_json(project_root() / "evaluation" / "goldens" / "page-116.json")
    rendered = render_page(page)
    assert '¼ "' in rendered
    assert '2¼ lb. apricots " "' in rendered


def test_deletion_is_excluded_and_correction_uses_replacement() -> None:
    lines = [
        {
            "line_number": 1,
            "segments": [
                {
                    "type": "deletion",
                    "medium": "typewritten",
                    "method": "strikethrough",
                    "reading": "Thursday",
                    "alternatives": [],
                    "confidence": "high",
                },
                {"type": "text", "text": " "},
                {
                    "type": "correction",
                    "medium": "typewritten",
                    "method": "struck_and_replaced",
                    "original": "19",
                    "replacement": "20",
                    "confidence": "high",
                },
            ],
            "line_end": "block_end",
        }
    ]
    assert render_lines(lines, diplomatic=False) == " 20"
    diplomatic = render_lines(lines, diplomatic=True)
    assert "deleted: Thursday" in diplomatic
    assert "19→20" in diplomatic


def test_graphical_feature_is_excluded_from_reading_text() -> None:
    page = {
        "blocks": [
            {
                "type": "graphical_feature",
                "description": "Small handwritten mark beneath the entry.",
            }
        ]
    }
    assert render_page(page) == ""
    assert render_page(page, diplomatic=True) == (
        "[graphical feature: Small handwritten mark beneath the entry.]"
    )
