"""Tests for revising a table's box to the true end of its content."""

from __future__ import annotations

import pytest

from quber.core.extractors.base import ExtractedTable
from quber.core.extractors.set_of_mark import extent
from quber.core.extractors.set_of_mark.extent import apply_content_regions, revise_content_region

# 100x100pt page; word tuples are (x0, y0, x1, y1, text) in top-left points.
LAST_ROW = [(10.0, 48.0, 30.0, 52.0, "Total"), (40.0, 48.0, 50.0, 52.0, "5")]
FOOTNOTE_BELOW = [(10.0, 68.0, 40.0, 72.0, "(1)"), (45.0, 68.0, 80.0, 72.0, "note")]
MD = "| a | b |\n|---|---|\n| Revenue | 9 |\n| Total | 5 |"


def test_revise_pulls_bottom_up_to_last_row():
    # som_region overruns to 0.80, enclosing a footnote line at y~70; the bottom
    # must snap up to the last tabular row at y~52, excluding the footnote.
    som = (0.1, 0.1, 0.9, 0.80)
    region = revise_content_region(som, MD, LAST_ROW + FOOTNOTE_BELOW, 100.0, 100.0)
    assert region[:3] == som[:3]  # left/top/right unchanged
    assert region[3] == pytest.approx(0.52)  # bottom revised to the last row


def test_revise_ignores_stacked_sibling_identical_row():
    # A stacked sibling's identical "Total 5" row sits at y~80, outside this
    # table's band (0.10..0.45); only the in-band row may move the bottom.
    som = (0.1, 0.1, 0.9, 0.45)
    words = [(10.0, 38.0, 30.0, 42.0, "Total"), (10.0, 78.0, 30.0, 82.0, "Total")]
    region = revise_content_region(som, MD, words, 100.0, 100.0)
    assert region[3] == pytest.approx(0.42)


def test_revise_falls_back_when_row_not_located():
    som = (0.1, 0.1, 0.9, 0.80)
    words = [(10.0, 20.0, 30.0, 24.0, "Unrelated")]
    assert revise_content_region(som, MD, words, 100.0, 100.0) == som


def test_revise_keeps_region_when_markdown_empty():
    som = (0.1, 0.1, 0.9, 0.80)
    assert revise_content_region(som, "", [], 100.0, 100.0) == som


def test_apply_sets_content_region(monkeypatch: pytest.MonkeyPatch):
    monkeypatch.setattr(extent, "page_words", lambda src, page: (100.0, 100.0, LAST_ROW + FOOTNOTE_BELOW))
    table = ExtractedTable(markdown=MD, page=1, som_region=(0.1, 0.1, 0.9, 0.80))
    apply_content_regions([table], "doc.pdf")
    assert table.content_region is not None
    assert table.content_region[3] == pytest.approx(0.52)


def test_apply_skips_table_without_som_region(monkeypatch: pytest.MonkeyPatch):
    monkeypatch.setattr(extent, "page_words", lambda src, page: (100.0, 100.0, []))
    table = ExtractedTable(markdown=MD, page=1)  # no som_region
    apply_content_regions([table], "doc.pdf")
    assert table.content_region is None
