"""Build a two-page PDF that prints both kinds of figure marker.

Page 1 prints a chart whose labels carry two references: a bare '1', defined by a
note at the foot of the page, and '(Note 16)', which names a section printed on
page 2 and is defined nowhere on page 1. The first is a footnote reference and
the second is a section cross-reference, so one document exercises both branches.

The chart is drawn as a raster image so the parse files the region as a picture,
which is what nominates the page. The notes and the heading are real PDF text, so
they reach the unified document as lines the resolution can search.
"""

from pathlib import Path

import pymupdf
from PIL import Image, ImageDraw, ImageFont

OUT = Path(__file__).with_name("note_reference.pdf")
CHART = Path(__file__).with_name("_chart.png")

W, H = 612, 792


def font(size: int) -> ImageFont.FreeTypeFont:
    for path in (
        "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
        "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
    ):
        if Path(path).exists():
            return ImageFont.truetype(path, size)
    return ImageFont.load_default()


def chart_png() -> None:
    """A bar chart whose title and one series label each carry a reference."""
    # Twice the placement size: enough that the labels stay crisp when the page
    # is rasterized for the agent, without the file growing past its neighbours.
    scale = 2
    w, h = 460 * scale, 300 * scale
    img = Image.new("RGB", (w, h), "white")
    d = ImageDraw.Draw(img)

    d.text(
        (14 * scale, 10 * scale),
        "TOTAL CONTRACTUAL OBLIGATIONS (Note 16)",
        font=font(15 * scale),
        fill="#12305a",
    )
    d.text(
        (14 * scale, 34 * scale),
        "Weighted Average Yield¹ by maturity year",
        font=font(11 * scale),
        fill="#555555",
    )

    bars = [("2026", 310), ("2027", 425), ("2028", 560), ("2029", 288)]
    base_y = 250 * scale
    top = 70 * scale
    for i, (year, value) in enumerate(bars):
        x = (60 + i * 95) * scale
        bar_h = int((value / 600) * (base_y - top))
        d.rectangle([x, base_y - bar_h, x + 58 * scale, base_y], fill="#2f6fb2")
        d.text(
            (x + 6 * scale, base_y - bar_h - 20 * scale), f"${value}", font=font(12 * scale), fill="#12305a"
        )
        d.text((x + 14 * scale, base_y + 8 * scale), year, font=font(12 * scale), fill="#333333")

    d.line([(46 * scale, base_y), (w - 20 * scale, base_y)], fill="#999999", width=2 * scale)
    for tick in (0, 150, 300, 450, 600):
        y = base_y - int((tick / 600) * (base_y - top))
        d.text((16 * scale, y - 7 * scale), f"{tick}", font=font(10 * scale), fill="#777777")

    img.save(CHART, optimize=True)


def build() -> None:
    chart_png()
    doc = pymupdf.open()

    page = doc.new_page(width=W, height=H)
    page.insert_text((54, 64), "PORTFOLIO OVERVIEW", fontsize=17, fontname="hebo", color=(0.07, 0.19, 0.35))
    page.insert_image(pymupdf.Rect(54, 90, 558, 419), filename=str(CHART))
    page.insert_text(
        (54, 470),
        "Obligations shown at carrying value. Amounts in millions.",
        fontsize=9,
        fontname="helv",
        color=(0.3, 0.3, 0.3),
    )
    page.insert_text(
        (54, 700),
        "1.  Weighted average yield is calculated on amortized cost as of March 31, 2026",
        fontsize=8,
        fontname="helv",
        color=(0.35, 0.35, 0.35),
    )
    page.insert_text((300, 750), "1", fontsize=8, fontname="helv", color=(0.5, 0.5, 0.5))

    page = doc.new_page(width=W, height=H)
    page.insert_text(
        (54, 64),
        "NOTE 16. COMMITMENTS AND CONTINGENCIES",
        fontsize=15,
        fontname="hebo",
        color=(0.07, 0.19, 0.35),
    )
    for i, line in enumerate(
        [
            "The Company is party to unfunded loan commitments arising in the normal course",
            "of business. At March 31, 2026 the aggregate unfunded commitment was $1,284",
            "million, of which $412 million is expected to fund within twelve months.",
            "",
            "The Company is not presently a party to any material legal proceedings other",
            "than ordinary routine litigation incidental to its business.",
        ]
    ):
        page.insert_text((54, 100 + i * 18), line, fontsize=10, fontname="helv", color=(0.15, 0.15, 0.15))
    page.insert_text((300, 750), "2", fontsize=8, fontname="helv", color=(0.5, 0.5, 0.5))

    doc.save(OUT, deflate=True, garbage=4)
    doc.close()
    CHART.unlink(missing_ok=True)
    print(f"wrote {OUT}")


build()
