"""Reproducible, synthetic PDF compression fixtures (no personal information)."""
from io import BytesIO
from pathlib import Path
import math
import random

from PIL import Image, ImageDraw, ImageFont, ImageFilter
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas

OUT = Path(__file__).parent / "fixtures"
OUT.mkdir(parents=True, exist_ok=True)
R = random.Random(20261020)
FONT = "/System/Library/Fonts/Supplemental/Arial.ttf"
FONT_BOLD = "/System/Library/Fonts/Supplemental/Arial Bold.ttf"


def write_vector_page(c, title, page, footer="Fictional test document · 2026"):
    w, h = A4
    c.setFillColorRGB(.10, .17, .24)
    c.setFont("Helvetica-Bold", 18)
    c.drawString(45, h - 55, title)
    c.setStrokeColorRGB(.22, .42, .52)
    c.line(45, h - 69, w - 45, h - 69)
    c.setFont("Helvetica", 9)
    c.setFillColorRGB(.2, .25, .3)
    c.drawString(45, 30, footer)
    c.drawRightString(w - 45, 30, str(page))


def fake_photo(width=1800, height=1150, seed=6):
    r = random.Random(seed)
    im = Image.new("RGB", (width, height))
    px = im.load()
    # A textured landscape with gradients: image-heavy but reproducible.
    hills = [height * (.42 + .035 * math.sin(x / 118) + .022 * math.sin(x / 37)) for x in range(width)]
    for y in range(height):
        for x in range(width):
            grain = r.randrange(-12, 13)
            if y < hills[x]:
                v = y / height
                px[x, y] = (max(0, min(255, int(110 + 65*v + grain))),
                            max(0, min(255, int(160 + 58*v + grain))),
                            max(0, min(255, int(205 + 27*v + grain))))
            else:
                v = (y - hills[x]) / (height - hills[x])
                px[x, y] = (max(0, min(255, int(83 + 73*v + grain))),
                            max(0, min(255, int(118 + 42*v + grain))),
                            max(0, min(255, int(85 + 16*v + grain))))
    return im.filter(ImageFilter.GaussianBlur(.4))


def make_scan():
    w, h = 2480, 3508  # A4 at 300 dpi
    im = Image.new("L", (w, h), 246)
    pix = im.load()
    for y in range(h):
        for x in range(w):
            pix[x, y] = max(0, min(255, pix[x, y] + R.randrange(-11, 12)))
    d = ImageDraw.Draw(im)
    title = ImageFont.truetype(FONT_BOLD, 82)
    body = ImageFont.truetype(FONT, 42)
    small = ImageFont.truetype(FONT, 31)
    d.text((175, 155), "APPLICATION DOCUMENT CHECKLIST", font=title, fill=15)
    d.line((175, 267, w-175, 267), fill=30, width=4)
    lines = [
        "This is a fictional scanned document for PDF compression tests.",
        "Applicant: Sample Person        Reference: TEST-2026-001",
        "Please verify every letter, number, and check box after compression.",
        "A hard 200 KB limit may require visible changes to scanned text.",
    ]
    y = 355
    for line in lines:
        d.text((175, y), line, font=body, fill=24)
        y += 83
    for i in range(19):
        yy = 790 + i*126
        d.rectangle((180, yy, 236, yy+58), outline=25, width=4)
        d.text((275, yy+4), f"Item {i+1:02d}: sample supporting document / date 20 Oct 2026", font=body, fill=27)
        d.line((275, yy+77, w-180, yy+77), fill=110, width=2)
    d.text((180, h-300), "Fine print: 0123456789  ABCDEFGHIJKLMNOPQRSTUVWXYZ", font=small, fill=45)
    d.text((180, h-245), "All names and identifiers above are invented for testing.", font=small, fill=45)
    jpg = OUT / "scan-source.jpg"
    im.save(jpg, quality=94, subsampling=0)
    path = OUT / "scan.pdf"
    c = canvas.Canvas(str(path), pagesize=A4, pageCompression=1)
    c.drawImage(str(jpg), 0, 0, width=A4[0], height=A4[1])
    c.showPage(); c.save()
    return path


def make_mixed():
    photo = fake_photo()
    jpg = OUT / "mixed-source.jpg"
    photo.save(jpg, quality=94, subsampling=0)
    path = OUT / "mixed.pdf"
    c = canvas.Canvas(str(path), pagesize=A4, pageCompression=1)
    w, h = A4
    for p in range(1, 3):
        write_vector_page(c, "Field inspection report", p)
        c.setFont("Helvetica", 11)
        c.drawString(45, h-103, "Site: fictional research site. Observations recorded for testing only.")
        c.drawString(45, h-123, "Vector text should remain selectable after image compression.")
        c.drawImage(str(jpg), 45, h-520, width=w-90, height=340)
        c.setFont("Helvetica-Bold", 10)
        c.drawString(45, h-542, f"Figure {p}. Synthetic textured landscape for image-quality inspection.")
        for j in range(8):
            c.setFont("Helvetica", 9)
            c.drawString(45, h-575-j*23, f"Measurement {j+1}: {j*17+24}.2 units    Control label ABC-{p}{j:02d}    Status: complete")
        c.showPage()
    c.save()
    return path


def make_text_heavy():
    path = OUT / "text-heavy.pdf"
    c = canvas.Canvas(str(path), pagesize=A4, pageCompression=1)
    w, h = A4
    r = random.Random(8871)
    for p in range(1, 21):
        write_vector_page(c, "Detailed vector data appendix", p)
        c.setFont("Helvetica", 8)
        c.drawString(45, h-89, "Text remains selectable. Dense unique vector marks are intentionally difficult to shrink.")
        for j in range(110):
            y = h-112-j*6.15
            c.setFont("Helvetica", 5.5)
            c.drawString(45, y, f"{p:02d}-{j:03d}  SAMPLE  {r.randrange(100000,999999)}  {r.randrange(100000,999999)}")
            for k in range(7):
                c.setFillColorRGB(r.random(), r.random(), r.random())
                x = 265 + k*35
                c.rect(x, y, 12+r.random()*19, 2+r.random()*4, fill=1, stroke=0)
        c.showPage()
    c.save()
    return path


if __name__ == "__main__":
    for fn in (make_scan, make_mixed, make_text_heavy):
        p = fn()
        print(p.name, p.stat().st_size)
