#!/usr/bin/env python3
"""Apply the final approved commercial wording to the five-page prospectus."""

from pathlib import Path
import fitz


SOURCE = Path("/Users/saidzouhdi/Downloads/META2027_Sponsorship_US_English_v2.pdf")
SITE_ROOT = Path(__file__).parents[1]
OUTPUTS = [
    SITE_ROOT / "files" / "META2027_Sponsorship.pdf",
    Path(__file__).parent / "META2027_Sponsorship.pdf",
]
FONT = Path(__file__).parent / "fonts" / "VeraBd.ttf"
FONT_REGULAR = Path(__file__).parent / "fonts" / "Vera.ttf"


def redact_matches(page: fitz.Page, phrase: str) -> list[fitz.Rect]:
    rects = page.search_for(phrase)
    if not rects:
        raise RuntimeError(f"Text not found on page {page.number + 1}: {phrase}")
    for rect in rects:
        page.add_redact_annot(rect + (-1, -1, 1, 1), fill=(1, 1, 1))
    return rects


def main() -> None:
    doc = fitz.open(SOURCE)
    if len(doc) != 5:
        raise RuntimeError(f"Expected 5 pages, found {len(doc)}")

    page3 = doc[2]
    line = "Additional space: €150/m² • Academic and startup rates on request • Prices include VAT"
    rect = redact_matches(page3, line)[0]

    page4 = doc[3]
    additional_space = redact_matches(page4, "Additional space: €150/m²")[0]
    # Remove the bullet drawn separately to the left of this deleted line.
    page4.add_redact_annot(
        fitz.Rect(additional_space.x0 - 22, additional_space.y0 - 1,
                  additional_space.x1 + 1, additional_space.y1 + 1),
        fill=(1, 1, 1),
    )
    redact_matches(page4, "Extra exhibition space")
    redact_matches(page4, "€150/m²")

    page3.apply_redactions()
    page4.apply_redactions()
    page3.insert_font(fontname="meta-final-bold", fontfile=str(FONT))
    page3.insert_text(
        fitz.Point(rect.x0, rect.y1 - 0.8),
        "Prices include taxes.",
        fontsize=7.2,
        fontname="meta-final-bold",
        color=(198 / 255, 161 / 255, 91 / 255),
        overlay=True,
    )

    # Make clear that the priced workshop is an add-on, not the package entitlement
    # repeated with a second price.
    anchor = page4.search_for("Other sponsorship opportunities are available on request.")
    if not anchor:
        raise RuntimeError("Page 4 workshop-note anchor not found")
    page4.insert_font(fontname="meta-final-regular", fontfile=str(FONT_REGULAR))
    page4.insert_text(
        fitz.Point(anchor[0].x0, anchor[0].y1 + 8.5),
        "The €1,500 workshop is additional to the workshop included in each package.",
        fontsize=6.5,
        fontname="meta-final-regular",
        color=(43 / 255, 53 / 255, 63 / 255),
        overlay=True,
    )

    temporary = OUTPUTS[0].with_suffix(".final.tmp.pdf")
    doc.save(temporary, garbage=4, deflate=True)
    doc.close()
    data = temporary.read_bytes()
    temporary.unlink()
    for output in OUTPUTS:
        output.write_bytes(data)


if __name__ == "__main__":
    main()
