#!/usr/bin/env python3
"""Apply the approved US-English wording to the compact sponsorship PDF.

The venue's official name, Niagara Falls Convention Centre, is intentionally
left unchanged. The replacement spans use the PDF's own embedded DejaVu fonts.
"""

from pathlib import Path
import re
import fitz


SOURCE = Path(__file__).parents[1] / "files" / "META2027_Sponsorship.pdf"
FONT_DIR = Path(__file__).parent / "fonts"

REPLACEMENTS = {
    "organisation": "organization",
    "programme": "program",
    "specialised": "specialized",
    "organisers": "organizers",
    "organising": "organizing",
    "Programme": "Program",
}


def rgb(color: int) -> tuple[float, float, float]:
    return tuple(((color >> shift) & 255) / 255 for shift in (16, 8, 0))


def background(page: fitz.Page, rect: fitz.Rect) -> tuple[float, float, float]:
    """Sample immediately above a text span, away from the glyphs."""
    pix = page.get_pixmap(matrix=fitz.Matrix(3, 3), alpha=False)
    x = max(0, min(pix.width - 1, round((rect.x0 + 2) * 3)))
    y = max(0, min(pix.height - 1, round((rect.y0 - 1.5) * 3)))
    sample = pix.pixel(x, y)
    return tuple(v / 255 for v in sample[:3])


def main() -> None:
    doc = fitz.open(SOURCE)
    pending: list[tuple[fitz.Page, fitz.Point, str, float, tuple, Path, str]] = []

    for page_number, page in enumerate(doc):
        for block in page.get_text("dict")["blocks"]:
            for line in block.get("lines", []):
                for span in line["spans"]:
                    revised = span["text"]
                    for old, new in REPLACEMENTS.items():
                        revised = re.sub(rf"\b{re.escape(old)}\b", new, revised)
                    if revised == span["text"]:
                        continue

                    rect = fitz.Rect(span["bbox"])
                    page.add_redact_annot(rect + (-0.5, -0.5, 0.8, 0.5), fill=background(page, rect))
                    bold = "Bold" in span["font"]
                    fontfile = FONT_DIR / ("VeraBd.ttf" if bold else "Vera.ttf")
                    pending.append((page, fitz.Point(span["origin"]), revised, span["size"], rgb(span["color"]), fontfile, f"meta{page_number}{'b' if bold else 'r'}"))

    for page in doc:
        page.apply_redactions()
    for page, origin, text, size, color, fontfile, fontname in pending:
        page.insert_font(fontname=fontname, fontfile=str(fontfile))
        page.insert_text(origin, text, fontsize=size, fontname=fontname, color=color, overlay=True)

    output = SOURCE.with_suffix(".american.tmp.pdf")
    doc.save(output, garbage=4, deflate=True)
    doc.close()
    output.replace(SOURCE)


if __name__ == "__main__":
    main()
