"""cashcard.py: build the cash handout card (poidh #1510), a black-and-white business card, front and back.

  python3 cashcard.py      # writes ./out/: card.pdf (3.75 x 2.25 in, 0.125 in white bleed), sheet-letter.pdf and
                           # sheet-a4.pdf (10-up, crop marks, duplex), front.png / back.png (600 dpi), preview.jpg
Needs: headless Chrome or Chromium (set CHROME=/path/to/chrome), fontTools, pypdf, macOS `sips` for the JPEG preview,
and the variable fonts BodoniModa[opsz,wght].ttf, BodoniModa-Italic[opsz,wght].ttf and Inter[opsz,wght].ttf from
Google Fonts saved in ./fonts/ as BodoniModa.ttf, BodoniModa-Italic.ttf and Inter.ttf (plus their OFL.txt files).
The guilloche rosette is drawn here from sine-modulated circles and a hypotrochoid; no image generation.
Every element stays inside the 0.125 in safe zone, so the card survives a print shop's trim or a pair of scissors.
Card text and layout: CC0 1.0.
"""
import math, os, subprocess, shutil

D = os.path.dirname(os.path.abspath(__file__)); OUT = os.path.join(D, "out"); FONTS = os.path.join(D, "fonts")
CH = os.environ.get("CHROME", "chromium")
os.makedirs(OUT, exist_ok=True)

# Card geometry in CSS px (96 per inch). Trim 3.5 x 2 in = 336 x 192.
TW, TH = 336, 192
INK = "#000"

def path(points):
    return "M" + " L".join(f"{x:.1f},{y:.1f}" for x, y in points) + " Z"

def rosette(cx, cy, s=1.0):
    """Banknote-style guilloche, radius ~64*s px, as SVG elements."""
    el = []
    sw = 0.42
    # outer rope: sine-modulated circles, phase-shifted copies weave into a band
    for k in range(10):
        ph = k * math.pi / 10
        pts = [(cx + (58 + 5 * math.sin(20 * t + ph)) * s * math.cos(t), cy + (58 + 5 * math.sin(20 * t + ph)) * s * math.sin(t))
               for t in [i * 2 * math.pi / 400 for i in range(400)]]
        el.append(f'<path d="{path(pts)}" fill="none" stroke="{INK}" stroke-width="{sw}"/>')
    for r in (64.5, 51.5):
        el.append(f'<circle cx="{cx}" cy="{cy}" r="{r * s:.2f}" fill="none" stroke="{INK}" stroke-width="0.8"/>')
    # middle: hypotrochoid star (R/r = 17/7 closes after 7 turns), several sizes nested
    for i, d in enumerate((14, 12.5, 11, 9.5, 8)):
        R, r = 34.0, 14.0
        pts = []
        n = 1100
        for j in range(n):
            t = j * 2 * math.pi * 7 / n
            x = (R - r) * math.cos(t) + d * math.cos((R - r) / r * t)
            y = (R - r) * math.sin(t) - d * math.sin((R - r) / r * t)
            k = (47 - i * 2.2) / (R - r + d)
            pts.append((cx + x * k * s, cy + y * k * s))
        el.append(f'<path d="{path(pts)}" fill="none" stroke="{INK}" stroke-width="{sw}"/>')
    # inner: fine wave ring around the centre disc
    for k in range(4):
        ph = k * math.pi / 4
        pts = [(cx + (19 + 2.0 * math.sin(24 * t + ph)) * s * math.cos(t), cy + (19 + 2.2 * math.sin(28 * t + ph)) * s * math.sin(t))
               for t in [i * 2 * math.pi / 360 for i in range(360)]]
        el.append(f'<path d="{path(pts)}" fill="none" stroke="{INK}" stroke-width="0.3"/>')
    el.append(f'<circle cx="{cx}" cy="{cy}" r="{15.5 * s:.2f}" fill="#fff" stroke="{INK}" stroke-width="0.8"/>')
    el.append(f'<text x="{cx}" y="{cy + 3.1 * s:.2f}" text-anchor="middle" font-family="BM Label" font-weight="800" '
              f'font-size="{8.6 * s:.2f}" letter-spacing="0.6" fill="{INK}">CASH</text>')
    return "\n".join(el)

MICRO = "CASH IS PRIVATE · CASH WORKS OFFLINE · CASH IS OPEN TO ALL · CASH IS YOURS · "

def face_front():
    cx, cy = 268, 96
    return f"""
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {TW} {TH}" width="{TW}" height="{TH}">
<rect width="{TW}" height="{TH}" fill="#fff"/>
<defs><clipPath id="m"><rect x="24" y="0" width="{TW - 48}" height="{TH}"/></clipPath></defs>
<text clip-path="url(#m)" x="24" y="21.5" font-family="Inter SemiBold" font-weight="600" font-size="3.1" letter-spacing="0.35" fill="{INK}">{(MICRO * 4)[:250]}</text>
<line x1="24" y1="24" x2="{TW - 24}" y2="24" stroke="{INK}" stroke-width="0.6"/>
<line x1="24" y1="{TH - 24}" x2="{TW - 24}" y2="{TH - 24}" stroke="{INK}" stroke-width="0.6"/>
<text clip-path="url(#m)" x="24" y="{TH - 17.5}" font-family="Inter SemiBold" font-weight="600" font-size="3.1" letter-spacing="0.35" fill="{INK}">{(MICRO * 4)[37:287]}</text>
{rosette(cx, cy)}
<text font-family="BM Display" font-weight="700" font-size="29" fill="{INK}" letter-spacing="-0.3">
  <tspan x="23" y="72">I paid you</tspan><tspan x="23" y="101">in cash.</tspan></text>
<text x="24" y="124" font-family="BM Italic" font-style="italic" font-weight="500" font-size="17" fill="{INK}">On purpose.</text>
<text x="24" y="150" font-family="Inter Medium" font-weight="500" font-size="7.6" fill="{INK}">Thank you for taking it.</text>
<text x="24" y="160.5" font-family="Inter Bold" font-weight="700" font-size="7.6" fill="{INK}">Turn over to see why it matters →</text>
</svg>"""

ITEMS = [("PRIVATE", ["Leaves no record of who", "bought what, where or when."]),
         ("OFFLINE", ["Works when the power, the", "network or the bank is down."]),
         ("OPEN TO ALL", ["No account, no app, no", "card fees, no permission."]),
         ("YOURS", ["Nobody can freeze it or", "switch it off from afar."])]

def face_back():
    out = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {TW} {TH}" width="{TW}" height="{TH}">',
           f'<rect width="{TW}" height="{TH}" fill="#fff"/>',
           f'<text x="{TW / 2}" y="37" text-anchor="middle" font-family="BM Title" font-weight="700" font-size="10.8" '
           f'letter-spacing="1.6" fill="{INK}">WHY CASH STILL MATTERS</text>',
           f'<line x1="24" y1="27" x2="64" y2="27" stroke="{INK}" stroke-width="0.6"/>',
           f'<line x1="{TW - 64}" y1="27" x2="{TW - 24}" y2="27" stroke="{INK}" stroke-width="0.6"/>',
           f'<line x1="24" y1="30" x2="64" y2="30" stroke="{INK}" stroke-width="0.6"/>',
           f'<line x1="{TW - 64}" y1="30" x2="{TW - 24}" y2="30" stroke="{INK}" stroke-width="0.6"/>']
    col = [26, 176]; row = [58, 99]
    for i, (label, lines) in enumerate(ITEMS):
        x, y = col[i % 2], row[i // 2]
        out.append(f'<text x="{x}" y="{y}" font-family="BM Label" font-weight="800" font-size="9.4" letter-spacing="1.1" fill="{INK}">{label}</text>')
        for j, ln in enumerate(lines):
            out.append(f'<text x="{x}" y="{y + 11.5 + j * 9.6:.1f}" font-family="Inter Regular" font-weight="400" font-size="7.9" fill="{INK}">{ln}</text>')
    out.append(f'<line x1="{TW / 2}" y1="49" x2="{TW / 2}" y2="125" stroke="{INK}" stroke-width="0.4"/>')
    out.append(f'<text x="{TW / 2}" y="146" text-anchor="middle" font-family="BM Italic" font-style="italic" font-weight="500" '
               f'font-size="12.5" fill="{INK}">If we stop using it, we lose it.</text>')
    # call-to-action bar, inside the safe zone
    out.append(f'<rect x="24" y="154" width="{TW - 48}" height="16" fill="{INK}"/>')
    out.append(f'<text x="{TW / 2}" y="164.6" text-anchor="middle" font-family="Inter ExtraBold" font-weight="800" font-size="7.4" '
               f'letter-spacing="1.25" fill="#fff">USE CASH · ACCEPT CASH · PASS THIS CARD ON</text>')
    out.append("</svg>")
    return "\n".join(out)

# Static instances: Chrome turns variable fonts into bulky Type 3 glyphs in a PDF; static TrueType subsets stay small.
STATIC = {  # family -> (source, axis location, css weight, css style)
    "BM Display": ("BodoniModa.ttf", {"wght": 700, "opsz": 22}, 700, "normal"),
    "BM Title": ("BodoniModa.ttf", {"wght": 700, "opsz": 9}, 700, "normal"),
    "BM Label": ("BodoniModa.ttf", {"wght": 800, "opsz": 9}, 800, "normal"),
    "BM Italic": ("BodoniModa-Italic.ttf", {"wght": 500, "opsz": 12}, 500, "italic"),
    **{f"Inter {n}": ("Inter.ttf", {"wght": w, "opsz": 14}, w, "normal") for w, n in
       ((400, "Regular"), (500, "Medium"), (600, "SemiBold"), (700, "Bold"), (800, "ExtraBold"))},
}

def static_fonts():
    from fontTools.ttLib import TTFont
    from fontTools.varLib.instancer import instantiateVariableFont
    os.makedirs(os.path.join(FONTS, "static"), exist_ok=True)
    css = []
    for fam, (src, loc, w, style) in STATIC.items():
        out = os.path.join(FONTS, "static", fam.replace(" ", "-") + ".ttf")
        if not os.path.exists(out):
            instantiateVariableFont(TTFont(os.path.join(FONTS, src)), loc, updateFontNames=False).save(out)
        css.append(f"@font-face {{ font-family: '{fam}'; src: url('file://{out}'); font-weight: {w}; font-style: {style}; }}")
    return "\n".join(css)

FONTCSS = static_fonts()

def chrome(args):
    subprocess.run([CH, "--headless", "--disable-gpu", "--hide-scrollbars", "--allow-file-access-from-files",
                    "--run-all-compositor-stages-before-draw", "--virtual-time-budget=4000"] + args, check=True, capture_output=True)

def html(body, page_w, page_h, extra=""):
    return f"""<!doctype html><html><head><meta charset="utf-8"><style>{FONTCSS}
@page {{ size: {page_w}in {page_h}in; margin: 0 }}
html, body {{ margin: 0; padding: 0; background: #fff }}
.page {{ position: relative; width: {page_w}in; height: {page_h}in; overflow: hidden; page-break-after: always; break-after: page }}
.page:last-child {{ page-break-after: auto; break-after: auto }}
{extra}</style></head><body>{body}</body></html>"""

def write(name, text):
    p = os.path.join(OUT, name); open(p, "w").write(text); return p

def sheet_pdf(card_pdf, out, pw, ph):
    """10-up sheet in points. Each face of card.pdf becomes ONE form XObject clipped to the trim box and is placed ten
    times, so the sheet stays about the size of the card (Chrome would repeat every rosette path ten times)."""
    from pypdf import PdfReader, PdfWriter
    from pypdf.generic import ArrayObject, DecodedStreamObject, DictionaryObject, FloatObject, NameObject
    r, w = PdfReader(card_pdf), PdfWriter()
    cw, chh, bleed = 252, 144, 9
    mx, my = (pw - 2 * cw) / 2, (ph - 5 * chh) / 2
    for src in r.pages[:2]:
        form = DecodedStreamObject()
        form.set_data(src.get_contents().get_data())
        form.update({NameObject("/Type"): NameObject("/XObject"), NameObject("/Subtype"): NameObject("/Form"),
                     NameObject("/BBox"): ArrayObject([FloatObject(v) for v in (bleed, bleed, bleed + cw, bleed + chh)]),
                     NameObject("/Resources"): src["/Resources"].get_object().clone(w)})
        ref = w._add_object(form.flate_encode())
        ops = []
        for row in range(5):
            for col in range(2):
                ops.append(f"q 1 0 0 1 {mx + col * cw - bleed:.3f} {my + row * chh - bleed:.3f} cm /Card Do Q")
        ops.append("q 0.73 G 0.3 w")   # faint cut guides around every card
        ops += [f"{mx + col * cw:.3f} {my + row * chh:.3f} {cw} {chh} re S" for row in range(5) for col in range(2)]
        ops.append("Q q 0 G 0.5 w")    # crop marks outside the grid
        for col in range(3):
            x = mx + col * cw
            ops += [f"{x:.3f} {my - 22.5:.3f} m {x:.3f} {my - 6:.3f} l S", f"{x:.3f} {my + 5 * chh + 6:.3f} m {x:.3f} {my + 5 * chh + 22.5:.3f} l S"]
        for row in range(6):
            y = my + row * chh
            ops += [f"{mx - 22.5:.3f} {y:.3f} m {mx - 6:.3f} {y:.3f} l S", f"{mx + 2 * cw + 6:.3f} {y:.3f} m {mx + 2 * cw + 22.5:.3f} {y:.3f} l S"]
        ops.append("Q")
        page = w.add_blank_page(pw, ph)
        page[NameObject("/Resources")] = DictionaryObject({NameObject("/XObject"): DictionaryObject({NameObject("/Card"): ref})})
        content = DecodedStreamObject(); content.set_data("\n".join(ops).encode())
        page[NameObject("/Contents")] = w._add_object(content.flate_encode())
    w.write(out)

def main():
    front, back = face_front(), face_back()
    write("front.svg", front); write("back.svg", back)
    # 1) single card with 0.125 in white bleed: 3.75 x 2.25 in, 2 pages
    card = "".join(f'<div class="page"><div style="position:absolute;left:12px;top:12px;width:{TW}px;height:{TH}px">{f}</div></div>'
                   for f in (front, back))
    p = write("card.html", html(card, 3.75, 2.25))
    chrome([f"--print-to-pdf={os.path.join(OUT, 'card.pdf')}", "--no-pdf-header-footer", "file://" + p])
    # 2) PNG previews at 600 dpi (trim size 3.5 x 2 in -> 2100 x 1200)
    for nm, f in (("front", front), ("back", back)):
        p = write(f"{nm}.html", html(f'<div style="width:{TW}px;height:{TH}px">{f}</div>', 3.5, 2))
        chrome(["--force-device-scale-factor=6.25", f"--window-size={TW},{TH}", f"--screenshot={os.path.join(OUT, nm + '.png')}", "file://" + p])
    # 2b) one preview of both faces for the claim and the page (JPEG via macOS sips, kept under 100 KiB)
    card_css = f"width:{TW}px;height:{TH}px;margin:0 auto 22px;box-shadow:0 1px 2px rgba(0,0,0,.25),0 6px 18px rgba(0,0,0,.18)"
    prev = (f'<div style="width:420px;height:470px;background:#e9e9e9;padding-top:32px;box-sizing:border-box">'
            f'<div style="{card_css}">{front}</div><div style="{card_css}">{back}</div></div>')
    p = write("preview.html", html(prev, 4.375, 4.9))
    png = os.path.join(OUT, "preview.png")
    chrome(["--force-device-scale-factor=2", "--window-size=420,470", f"--screenshot={png}", "file://" + p])
    subprocess.run(["sips", "-s", "format", "jpeg", "-s", "formatOptions", "52", png, "--out", os.path.join(OUT, "preview.jpg")],
                   check=True, capture_output=True)
    os.remove(png)
    # 3) 10-up sheets (2 x 5, cards abut, crop marks outside the grid), front page then back page for long-edge duplex
    for sheet, (pw, ph) in (("letter", (612, 792)), ("a4", (595.28, 841.89))):
        sheet_pdf(os.path.join(OUT, "card.pdf"), os.path.join(OUT, f"sheet-{sheet}.pdf"), pw, ph)
    for f in os.listdir(OUT):
        if f.endswith(".html"): os.remove(os.path.join(OUT, f))
    for f in ("OFL-BodoniModa.txt", "OFL-Inter.txt"):
        shutil.copy(os.path.join(FONTS, f), OUT)
    print("\n".join(sorted(f"{f} {os.path.getsize(os.path.join(OUT, f))}" for f in os.listdir(OUT))))

if __name__ == "__main__":
    main()
