# retoor <retoor@molodetz.nl>
import argparse
import json
import os

PAGE_WIDTH = 210
MARGIN = 15
TITLE_SIZE = 20
HEADING_SIZE = 14
BODY_SIZE = 11
CAPTION_SIZE = 9


def build_pdf(title, sections, figures, out_path):
    from fpdf import FPDF

    pdf = FPDF(orientation="P", unit="mm", format="A4")
    pdf.set_auto_page_break(True, margin=MARGIN)
    pdf.set_margins(MARGIN, MARGIN, MARGIN)
    usable = PAGE_WIDTH - 2 * MARGIN
    pdf.add_page()
    pdf.set_font("Helvetica", "B", TITLE_SIZE)
    pdf.multi_cell(usable, 10, title, new_x="LMARGIN", new_y="NEXT")
    pdf.ln(4)
    for heading, body in sections:
        pdf.set_font("Helvetica", "B", HEADING_SIZE)
        pdf.multi_cell(usable, 8, heading, new_x="LMARGIN", new_y="NEXT")
        pdf.set_font("Helvetica", "", BODY_SIZE)
        pdf.multi_cell(usable, 6, body, new_x="LMARGIN", new_y="NEXT")
        pdf.ln(2)
    for entry in figures:
        path = entry[0] if isinstance(entry, (list, tuple)) else entry.get("path")
        caption = entry[1] if isinstance(entry, (list, tuple)) and len(entry) > 1 else entry.get("caption", "")
        if not path or not os.path.isfile(path):
            continue
        if pdf.get_y() > 180:
            pdf.add_page()
        pdf.image(path, w=usable)
        if caption:
            pdf.set_font("Helvetica", "I", CAPTION_SIZE)
            pdf.multi_cell(usable, 5, caption, new_x="LMARGIN", new_y="NEXT")
        pdf.ln(2)
    pdf.output(out_path)
    return out_path


def from_spec(spec):
    sections = [(row.get("heading", ""), row.get("body", "")) for row in spec.get("sections", [])]
    return spec.get("title", ""), sections, spec.get("figures", [])


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Build a PDF report embedding chart PNGs and credited images.")
    parser.add_argument("spec", help="JSON file with title, sections, and figures")
    parser.add_argument("output", help="Output PDF path")
    args = parser.parse_args()
    with open(args.spec, encoding="utf-8") as handle:
        title, sections, figures = from_spec(json.load(handle))
    print(build_pdf(title, sections, figures, args.output))
