"""Deterministic sheet-list reconciliation: cover index vs extracted sheets."""

from backend.sheet_reconcile import declared_sheet_list, reconcile_sheets

COVER_TEXT = """VERIZON CYPRESS
SHEET LIST
SHEET NUMBER
SHEET NAME
G000
COVER
G001
GENERAL INFO
C-001
CIVIL COVER
C-001.1
ALTA SURVEY
L-101
LANDSCAPE PLAN
S101
FOUNDATION PLAN
S301
WALL SECTIONS
S401
PERSPECTIVE VIEW
A101
FLOOR PLAN
A102
REFLECTED CEILING PLAN
E400
ELECTRICAL SITE PLAN
"""


def test_declared_sheet_list_from_cover():
    declared = declared_sheet_list({1: COVER_TEXT, 2: "symbols legend"})
    assert declared[0] == "G000"
    assert "C-001" in declared and "C-001.1" in declared  # hyphenated ids kept
    assert "L-101" in declared
    assert "A102" in declared
    assert declared.count("G000") == 1
    assert len(declared) == 11


def test_declared_sheet_list_uses_first_index_page_only():
    texts = {1: "no index here", 2: COVER_TEXT, 3: "SHEET LIST\nXX999\nBOGUS"}
    declared = declared_sheet_list(texts)
    assert "XX999" not in declared  # only the first marker page is parsed


def test_declared_sheet_list_none_when_no_marker():
    assert declared_sheet_list({1: "just notes", 2: "floor plan stuff"}) == []


def _sheets(*nums):
    return [{"page_number": i + 1, "sheet_number": n}
            for i, n in enumerate(nums)]


def test_reconcile_both_directions():
    declared = declared_sheet_list({1: COVER_TEXT})
    rec = reconcile_sheets(_sheets("G000", "G001", "S101", "S301", "S302", "A101"),
                           declared)
    # declared but not extracted (civil/landscape not in this PDF + missing)
    assert "C-001" in rec["declared_not_in_set"]
    assert "A102" in rec["declared_not_in_set"]
    assert "E400" in rec["declared_not_in_set"]
    # extracted but not on the cover index (misread or unlisted sheet)
    assert rec["in_set_not_declared"] == ["S302"]
    assert rec["declared_total"] == 11
    assert rec["found_total"] == 6


def test_reconcile_normalizes_hyphens():
    declared = ["C-001", "S301"]
    rec = reconcile_sheets(_sheets("C001", "S301"), declared)
    assert rec["declared_not_in_set"] == []
    assert rec["in_set_not_declared"] == []


def test_reconcile_ignores_unidentified_sheets():
    rec = reconcile_sheets(
        [{"page_number": 8, "sheet_number": None},
         {"page_number": 9, "sheet_number": "S301"}],
        ["S301", "A102"])
    assert rec["found_total"] == 1
    assert rec["declared_not_in_set"] == ["A102"]
