"""Unanchored figure values become searchable records; anchored ones do not."""

from __future__ import annotations

from quber.core.figures.models import FigureValue
from quber.playground.ingest_fusion import _unanchored_value_records


def _value(page: int, label: str, value: str, picture_ref: str | None = None, **kw) -> FigureValue:
    return FigureValue(
        page=page, label=label, value=value, status="value_unreconciled", picture_ref=picture_ref, **kw
    )


def test_unanchored_values_group_into_one_record_per_page():
    values = [
        ("fv-0", _value(3, "Real Estate", "$314B", chart_title="Business Under Management")),
        ("fv-1", _value(3, "Credit & Insurance", "$99B")),
        ("fv-2", _value(4, "Blackstone Real Estate portfolio companies", "63")),
    ]
    records = _unanchored_value_records(values, {3: "Blackstone Overview", 4: "BREDS Platform"})

    assert [r[0] for r in records] == ["figure-values-p3", "figure-values-p4"]
    ref_id, ref_type, page0, bbox, content, parent = records[0]
    assert ref_type == "figure_values"
    assert page0 == 2  # stored 0-based
    assert bbox is None and parent is None  # no value carried a box
    # Each line is id-tagged so the answer agent cites the value's own
    # grounding, which is the tight per-value overlay.
    assert "[fv-0] " in content and "Real Estate: $314B" in content
    assert "[fv-1] " in content and "Credit & Insurance: $99B" in content
    assert content.startswith("Blackstone Overview — ")
    assert "Business Under Management" in content

    assert "[fv-2] Blackstone Real Estate portfolio companies: 63" in records[1][4]


def test_record_never_carries_a_box_even_when_its_values_do():
    """A synthetic record box renders as a misleading figure-sized highlight
    painted over the values' tight ones. Only the values' own boxes draw."""
    values = [
        ("fv-0", _value(3, "A", "1")),
        ("fv-1", _value(3, "B", "2")),
    ]
    values[0][1].box = {"left": 0.1, "top": 0.4, "right": 0.2, "bottom": 0.5}
    values[1][1].box = {"left": 0.6, "top": 0.2, "right": 0.7, "bottom": 0.3}
    (record,) = _unanchored_value_records(values, {})
    assert record[3] is None


def test_anchored_values_produce_no_record():
    values = [
        ("fv-0", _value(7, "Fixed", "2%", picture_ref="#/pictures/4")),
        ("fv-1", _value(7, "Floating", "98%", picture_ref="#/pictures/4")),
    ]
    assert _unanchored_value_records(values, {7: "Loan Portfolio"}) == []


def test_page_without_heading_gets_bare_lines():
    records = _unanchored_value_records([("fv-0", _value(9, "San Jose, CA", "3"))], {})
    assert records[0][4] == "[fv-0] San Jose, CA: 3"
