from __future__ import annotations
import csv
from pathlib import Path


CM_PER_PT = 2.54 / 72.0
DPI_PAIR_THRESHOLD = 0.5


def _pt_to_cm(pt: float) -> float:
    return pt * CM_PER_PT


def _fmt_dpi_pair(dx: float | None, dy: float | None) -> str:
    if dx is None or dy is None:
        return ""
    if abs(dx - dy) < DPI_PAIR_THRESHOLD:
        return f"{dx:.1f}"
    else:
        return f"{dx:.1f}×{dy:.1f}"


def _fmt_bbox_cm(x0_pt: float, y0_pt: float, x1_pt: float, y1_pt: float) -> str:
    x0, y0, x1, y1 = (_pt_to_cm(v) for v in (x0_pt, y0_pt, x1_pt, y1_pt))
    return f"({x0:.2f}, {y0:.2f}) – ({x1:.2f}, {y1:.2f})"


def fmt_page_dims(w_pt: float, h_pt: float) -> str:
    w_cm = _pt_to_cm(w_pt)
    h_cm = _pt_to_cm(h_pt)
    return f"{w_cm:.2f} × {h_cm:.2f}"


def print_report(page_index: int, page_w_pt: float, page_h_pt: float, occurrences: list[dict], suspected_tiling: bool = False) -> None:
    print(f"\n=== Page {page_index}: {len(occurrences)} image draws — Page dimensions: {fmt_page_dims(page_w_pt, page_h_pt)} cm ===")

    if suspected_tiling:
        print(" [warning] This page may contain a single image flattened into many tiles.")

    for rec in occurrences:
        dx, dy = rec.get("dpi_pair", (None, None))
        x0, y0, x1, y1 = rec["bbox_pt"]
        dpi_txt = _fmt_dpi_pair(dx, dy)
        bbox_txt = _fmt_bbox_cm(x0, y0, x1, y1) + " [cm]"
        print(f" {rec['image_id']:>9}  DPI={dpi_txt:<11}  {bbox_txt:<36}")


def write_csv(rows: list[dict], csv_path: Path) -> None:
    csv_path.parent.mkdir(parents=True, exist_ok=True)
    with csv_path.open("w", newline="", encoding="utf-8") as f:
        w = csv.writer(f)
        w.writerow([
            "Page",
            "Image ID",
            "DPI",
            "Shadow clip [0-100 %]",
            "Highlight clip [0-100 %]",
            "Contrast [0-100 %]",
            "Colorfulness (HS) [0-N/A]",
            "Color richness [0-100 %]",
            "BBox [cm]",
            "Page dimensions [cm]",
            "Recommendations",
            "Recommendations (long)",
        ])
        for r in rows:
            dx, dy = r.get("dpi_pair", (None, None))
            x0, y0, x1, y1 = r["bbox_pt"]

            w.writerow([
                r["page"],
                r["image_id"],
                _fmt_dpi_pair(dx, dy),
                r.get("shadow_clip_pct", ""),
                r.get("highlight_clip_pct", ""),
                r.get("contrast_p1p99_pct", ""),
                r.get("colorfulness_hs", ""),
                r.get("color_richness_pct", ""),
                _fmt_bbox_cm(x0, y0, x1, y1),
                r.get("page_dims", ""),
                r.get("recommendations", ""),
                r.get("recommendations_long", ""),
            ])