"""Generate matching text-layer and image-only synthetic PDFs locally.

Requires reportlab and the Poppler pdftoppm executable. No model or network calls.
"""

import argparse
import shutil
import subprocess
from pathlib import Path
from tempfile import TemporaryDirectory

from reportlab.lib.colors import HexColor
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas


WIDTH, HEIGHT = letter


def make_canvas(path):
    result = canvas.Canvas(str(path), pagesize=letter, invariant=1)
    result.setTitle("AIXiamo PDF reading check - synthetic fixture")
    result.setAuthor("AIXiamo")
    result.setSubject("Synthetic content. Not customer data. Not a live ChatGPT test.")
    return result


def frame(pdf, number, heading):
    pdf.setFillColor(HexColor("#16806a"))
    pdf.rect(48, HEIGHT - 66, 516, 4, fill=1, stroke=0)
    pdf.setFillColor(HexColor("#18231f"))
    pdf.setFont("Helvetica-Bold", 23)
    pdf.drawString(48, HEIGHT - 109, heading)
    pdf.setFont("Helvetica", 11)
    pdf.setFillColor(HexColor("#516159"))
    pdf.drawString(48, HEIGHT - 137, "AIXiamo | PDF reading check | synthetic data")
    pdf.setFont("Helvetica", 10)
    pdf.drawString(48, 42, f"Printed page A-0{number}")
    pdf.drawRightString(WIDTH - 48, 42, f"Physical page {number} of 3")


def lines(pdf, text, y, size=13, leading=23):
    pdf.setFillColor(HexColor("#18231f"))
    pdf.setFont("Helvetica", size)
    for line in text:
        pdf.drawString(48, y, line)
        y -= leading


def build_text_pdf(path):
    pdf = make_canvas(path)
    frame(pdf, 1, "Check the source, page by page")
    lines(pdf, [
        "Marker: PDF-CHECK-P1",
        "This document has three physical pages.",
        "Printed page labels are A-01, A-02 and A-03.",
        "Table 1 is on physical page 2; the footnote is on page 3.",
    ], HEIGHT - 195)
    lines(pdf, [
        "Synthetic fixture: all amounts and records are invented.",
        "The text-layer and image-only versions show the same content.",
        "This is not a live ChatGPT test or a model accuracy score.",
    ], HEIGHT - 353, size=11, leading=21)
    pdf.showPage()

    frame(pdf, 2, "Table 1 - synthetic amounts")
    lines(pdf, ["Marker: PDF-CHECK-P2", "Currency: CNY"], HEIGHT - 191)
    left, top, row_height, table_width = 48, HEIGHT - 263, 44, 516
    pdf.setFillColor(HexColor("#edf5f2"))
    pdf.rect(left, top - row_height, table_width, row_height, fill=1, stroke=0)
    data = [
        ("Record ID", "Amount (CNY)"),
        ("A", "12.30"),
        ("B", "45.60"),
        ("C", "7.89"),
        ("TOTAL", "65.79"),
    ]
    for index, (record, amount) in enumerate(data):
        y = top - row_height * index
        pdf.setStrokeColor(HexColor("#cbd8d2"))
        pdf.line(left, y - row_height, left + table_width, y - row_height)
        pdf.setFillColor(HexColor("#18231f"))
        pdf.setFont("Helvetica-Bold" if index in (0, 4) else "Helvetica", 14)
        pdf.drawString(left + 14, y - 28, record)
        pdf.drawRightString(left + table_width - 14, y - 28, amount)
    lines(pdf, [
        "Read the headers, unit, all three data rows and total.",
        "Check the footnote on physical page 3 before using the result.",
    ], HEIGHT - 540, size=11, leading=21)
    pdf.showPage()

    frame(pdf, 3, "Footnote and final-page check")
    lines(pdf, [
        "Marker: PDF-CHECK-P3",
        "Amounts exclude tax. Table 1 has 3 data rows.",
        "Calculation: 12.30 + 45.60 + 7.89 = 65.79 CNY.",
    ], HEIGHT - 195)
    lines(pdf, [
        "Use this final-page note to check coverage.",
        "A plausible total alone does not verify the whole document.",
    ], HEIGHT - 346, size=11, leading=21)
    pdf.save()


def generate(output):
    output.mkdir(parents=True, exist_ok=True)
    text_pdf = output / "text-layer.pdf"
    build_text_pdf(text_pdf)
    with TemporaryDirectory(prefix="aixiamo-pdf-check-") as temporary:
        prefix = Path(temporary) / "page"
        subprocess.run([
            "pdftoppm", "-r", "150", "-png", str(text_pdf), str(prefix),
        ], check=True)
        images = sorted(Path(temporary).glob("page-*.png"))
        if len(images) != 3:
            raise RuntimeError("Expected exactly three rendered pages.")
        image_pdf = make_canvas(output / "image-only.pdf")
        for image in images:
            image_pdf.drawImage(str(image), 0, 0, width=WIDTH, height=HEIGHT)
            image_pdf.showPage()
        image_pdf.save()
        shutil.copyfile(images[1], output / "table-page.png")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output-dir", type=Path, default=Path(__file__).resolve().parent)
    args = parser.parse_args()
    generate(args.output_dir)
    print("Generated text-layer.pdf, image-only.pdf and table-page.png (3 pages each).")


if __name__ == "__main__":
    main()
