"""Annotated PDF: the source pages with each table's final boundary drawn on.

Each table's ``content_region`` (the corrected end of the table at its last data
row) is drawn onto its page with a small ordinal+title label, so a reviewer can
see at a glance which regions were located and how they map onto the source.
Falls back to ``som_region`` when a located table has no ``content_region``.
Engines without the Set-of-Mark locator set neither region, so their tables are
not drawn. The tables are supplied already-extracted, so this does no
extraction of its own.
"""

from __future__ import annotations

from pathlib import Path
from typing import Sequence

import fitz

from quber.core.extractors import ExtractedTable

BOX_RGB = (0.0, 0.32, 0.92)


def render_annotated_pdf(tables: Sequence[ExtractedTable], pdf: Path, out_path: Path) -> Path:
    """Draw each table's final boundary (``content_region``, else ``som_region``)
    onto a copy of ``pdf``.

    One box per located table; pages with no tables are left untouched. Tables
    with neither region (engines that do not run the locator) are skipped.
    Returns ``out_path``.
    """
    doc = fitz.open(str(pdf))
    drawn = 0
    for t in tables:
        region = t.content_region or t.som_region
        if not region:
            continue
        page = doc[t.page - 1]
        w, h = page.rect.width, page.rect.height
        x0, y0, x1, y1 = region
        rect = fitz.Rect(min(x0, x1) * w, min(y0, y1) * h, max(x0, x1) * w, max(y0, y1) * h)
        page.draw_rect(rect, color=BOX_RGB, width=1.4)
        label = f"{t.page}.{drawn + 1}: {t.title}" if t.title else f"{t.page}.{drawn + 1}"
        page.insert_text((rect.x0 + 2, max(8.0, rect.y0 - 3)), label, fontsize=6, color=BOX_RGB)
        drawn += 1
    out_path.parent.mkdir(parents=True, exist_ok=True)
    doc.save(str(out_path))
    return out_path
