"""Review artifacts draw the final content_region box, not the overrunning region."""

from __future__ import annotations

import base64
import io
from pathlib import Path

from PIL import Image as PImage

from quber.core.extractors.base import ExtractedTable, GroundedCell
from quber.review.flags import render_flags_html
from quber.review.html import before_b64


def test_before_b64_box_and_crop_use_separate_regions():
    # The drawn box is the (smaller) content_region; the crop follows the (larger)
    # som_region so the area below the box stays visible. The cropped image's size
    # must track the crop region, not the box.
    img = PImage.new("RGB", (100, 100), (255, 255, 255))
    box = (0.10, 0.10, 0.50, 0.40)  # final boundary (content_region)
    crop_region = (0.05, 0.05, 0.90, 0.80)  # broader located region (som_region)

    out = PImage.open(io.BytesIO(base64.b64decode(before_b64(img, box, crop_region))))

    mx, my = 0.025, 0.012
    expected_w = int(min(1.0, 0.90 + mx) * 100) - int(max(0.0, 0.05 - mx) * 100)
    expected_h = int(min(1.0, 0.80 + my) * 100) - int(max(0.0, 0.05 - my) * 100)
    assert abs(out.size[0] - expected_w) <= 1
    assert abs(out.size[1] - expected_h) <= 1
    # The blue box outline is drawn somewhere in the crop.
    colors = out.getcolors(maxcolors=1 << 24) or []
    assert any(color == (0, 90, 235) for _count, color in colors)


def _table(cells, **kw):
    grid = [
        [GroundedCell(text=text, status=status, note=note) for text, status, note in row] for row in cells
    ]
    return ExtractedTable(
        markdown="| a |\n| --- |\n| 1 |",
        page=1,
        corrected_grid=grid,
        som_region=(0.1, 0.1, 0.9, 0.5),
        content_region=(0.1, 0.1, 0.9, 0.45),
        **kw,
    )


def test_render_flags_html_shows_every_flagged_decision(tmp_path, monkeypatch):
    # Defect, unverified, AND supplied cells get highlighted with reasoning
    # lines; dropped printed text is listed table-level; measured cells get
    # neither.
    monkeypatch.setattr(
        "quber.review.flags.render_flag_page",
        lambda pdf, page, dpi: PImage.new("RGB", (80, 60), (255, 255, 255)),
    )
    table = _table(
        [
            [
                ("Payor", "unverified", "nothing printed at the header position"),
                ("2022", "reconciled", None),
            ],
            [
                ("Total", "total_label_added", "the row visibly totals its section"),
                ("$ 5", "reconciled", None),
            ],
            [("Rate(1)", "defect", "the page prints 'Effective Rate(1)' here"), ("9%", "reconciled", None)],
        ],
        table_id="doc-p1-t1",
        title="Revenue by payor",
        dropped_text=["Attachment 1"],
    )
    out = tmp_path / "doc.flags.html"

    assert render_flags_html([(Path("doc.pdf"), [table])], out) == out
    html = out.read_text()
    assert 'class="unverified">Payor' in html
    assert 'class="defect">Rate(1)' in html
    assert 'class="total_label_added">Total' in html
    assert "the page prints &#x27;Effective Rate(1)&#x27; here" in html
    assert "the row visibly totals its section" in html
    assert "header_text_dropped</span> 'Attachment 1'" in html
    assert "doc-p1-t1: Revenue by payor" in html
    assert "data:image/png;base64," in html


def test_render_flags_html_writes_nothing_without_flagged_decisions(tmp_path):
    table = _table([[("Revenue", "reconciled", None), ("$ 5", "reconciled", None)]])
    out = tmp_path / "doc.flags.html"

    assert render_flags_html([(Path("doc.pdf"), [table])], out) is None
    assert not out.exists()
