from __future__ import annotations

from copy import deepcopy

from crowley_diary.reconciliation import reconcile_adjacent_pages
from crowley_diary.validation import validate_reciprocal_pages


def page(number: int, block_id: str, from_previous: str, to_next: str) -> dict:
    return {
        "page_id": f"page-{number:03d}",
        "source": {"pdf_page": number},
        "blocks": [
            {
                "id": block_id,
                "type": "letter",
                "continuation": {
                    "from_previous": from_previous,
                    "to_next": to_next,
                    "previous": None,
                    "next": None,
                },
            }
        ],
        "provenance": {"steps": []},
    }


def test_reconciliation_adds_reciprocal_links_only_after_both_pages_exist() -> None:
    left = page(127, "p127-b001", "no", "yes")
    right = page(128, "p128-b001", "yes", "no")
    assert left["blocks"][0]["continuation"]["next"] is None
    result = reconcile_adjacent_pages(left, right)
    assert result.unresolved_left == []
    assert left["blocks"][0]["continuation"]["next"] == {
        "page_id": "page-128",
        "block_id": "p128-b001",
    }
    assert right["blocks"][0]["continuation"]["previous"] == {
        "page_id": "page-127",
        "block_id": "p127-b001",
    }
    assert validate_reciprocal_pages([left, right]).valid


def test_ambiguous_reconciliation_remains_unresolved() -> None:
    left = page(10, "p010-b001", "no", "yes")
    left["blocks"].append(deepcopy(left["blocks"][0]))
    left["blocks"][1]["id"] = "p010-b002"
    right = page(11, "p011-b001", "yes", "no")
    result = reconcile_adjacent_pages(left, right)
    assert result.unresolved_left
    assert result.warnings

