#!/usr/bin/env python3
"""Builds the Go Around membership badges as standalone SVGs. Text is outlined (no font needed).
Run with a python that has fontTools + brotli. Sources: components/pilot-ato-wired-19nov (user.css .pass/.tag, ga.css tokens,
shared/badges/*.svg) on go-around-design main (PR #16)."""
import re, os
from fontTools.ttLib import TTFont
from fontTools.pens.svgPathPen import SVGPathPen
from fontTools.pens.transformPen import TransformPen

HERE = os.path.dirname(os.path.abspath(__file__))
FONT = TTFont(os.path.join(HERE, '..', 'fonts', 'general-sans-600.woff2'))
GS = FONT.getGlyphSet(); CMAP = FONT.getBestCmap(); UPM = FONT['head'].unitsPerEm
CAP = FONT['OS/2'].sCapHeight

def text_path(text, size, track_em, x, cy):
    """Outlined text, left edge x, cap-height centred on cy. Returns (d, width)."""
    s = size / UPM; pen = SVGPathPen(GS, ntos=lambda v: f"{v:.2f}".rstrip('0').rstrip('.'))
    base = cy + (CAP * s) / 2; cx = x
    for i, ch in enumerate(text):
        g = CMAP[ord(ch)]
        tp = TransformPen(pen, (s, 0, 0, -s, cx, base)); GS[g].draw(tp)
        cx += GS[g].width * s + (track_em * size if i < len(text) - 1 else 0)
    return pen.getCommands(), cx - x

def seal_paths():
    t = open('/tmp/ato-src.svg').read()
    ds = re.findall(r'd="([^"]{200,})"', t)  # [body, glass, spec, stroke, tick]
    return ds
SEAL = seal_paths()
COMPASS = re.search(r'<path fill="url\(#fgGold\)" d="([^"]+)"', open('/tmp/compass-src.svg').read()).group(1)

def seal(fill, tick, uid, x, y, size, mono=None):
    """Scalloped verified seal from the site (24x24 source), placed at x,y with given size."""
    k = size / 24
    g = f'<g transform="translate({x} {y}) scale({k})">'
    if mono == 'outline':
        g += f'<path d="{SEAL[0]}" fill="#fff" stroke="#111" stroke-width="1.1"/><path d="{SEAL[4]}" fill="#111"/>'
    elif mono == 'solid':
        g += f'<path d="{SEAL[0]}" fill="#111"/><path d="{SEAL[4]}" fill="#fff"/>'
    else:
        g += (f'<path d="{SEAL[0]}" fill="{fill}"/><path d="{SEAL[1]}" fill="url(#{uid}Glass)"/>'
              f'<path d="{SEAL[2]}" fill="url(#{uid}Spec)"/><path d="{SEAL[3]}" fill="none" stroke="#000" stroke-opacity=".22" stroke-width=".5"/>'
              f'<path d="{SEAL[4]}" fill="#fff"/>')
    return g + '</g>'

def seal_defs(uid):
    return (f'<linearGradient id="{uid}Glass" x1="5" y1="3" x2="19" y2="21" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#fff" stop-opacity=".36"/><stop offset=".5" stop-color="#fff" stop-opacity="0"/><stop offset="1" stop-color="#000" stop-opacity=".18"/></linearGradient>'
            f'<linearGradient id="{uid}Spec" x1="12" y1="1.5" x2="12" y2="9" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#fff" stop-opacity=".42"/><stop offset="1" stop-color="#fff" stop-opacity="0"/></linearGradient>')

H = 26; R = 13; SZ = 11; TR = .10   # .tag: 26px high, pill, General Sans 600 11px, .1em, uppercase

def svg(w, h, title, defs, body):
    return (f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w:.2f} {h}" width="{w:.0f}" height="{h}" role="img" aria-label="{title}">\n'
            f'  <title>{title}</title>\n  <defs>{defs}</defs>\n  {body}\n</svg>\n')

def compass(x, y, size, fill):
    k = size / 24
    return f'<g transform="translate({x} {y}) scale({k})"><path d="{COMPASS}" fill="{fill}"/></g>'

OUT = {}
OVL = lambda w: f'<rect x="1" y="1" width="{w-2:.2f}" height="{H-2}" rx="{R-1}" fill="url(#g)"/>'

def pill(name, label, bg_defs, bg_fill, border, textcol, lead=None, lead_w=0, extra=''):
    d, tw = text_path(label.upper(), SZ, TR, 0, 0)
    padL = 10 if not lead else 4 + lead_w + 7
    d, tw = text_path(label.upper(), SZ, TR, padL, H / 2)
    w = padL + tw + 11
    body = (f'<rect x=".5" y=".5" width="{w-1:.2f}" height="{H-1}" rx="{R-.5}" fill="{bg_fill}" stroke="{border}" stroke-width="1"/>' + (extra(w) if callable(extra) else extra)
            + (lead or '') + f'<path d="{d}" fill="{textcol}"/>')
    return w, body

# ---------- colour (as the site shows them) ----------
# Free: .pass.free graphite. Trial: graphite lit with theme accent (#0019C9 Pearl/Champagne). Pro: deep steel. Founding: gold foil.
def colour():
    out = {}
    # Free
    defs = ('<radialGradient id="g" cx="0" cy="0" r="1.25" gradientUnits="objectBoundingBox"><stop offset="0" stop-color="#fff" stop-opacity=".10"/><stop offset=".55" stop-color="#fff" stop-opacity="0"/></radialGradient>'
            '<linearGradient id="b" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#1C1D21"/><stop offset=".52" stop-color="#2B2C32"/><stop offset="1" stop-color="#17181B"/></linearGradient>')
    w, body = pill('free', 'Free', defs, 'url(#b)', 'rgba(214,220,232,.30)', '#F2F3F5', extra=OVL)
    out['free'] = svg(w, H, 'Free', defs, body)
    # Trial
    defs = ('<radialGradient id="g" cx="0" cy="0" r="1.1" gradientUnits="objectBoundingBox"><stop offset="0" stop-color="#0019C9" stop-opacity=".62"/><stop offset=".6" stop-color="#0019C9" stop-opacity="0"/></radialGradient>'
            '<linearGradient id="b" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#1C1D21"/><stop offset=".52" stop-color="#2B2C32"/><stop offset="1" stop-color="#17181B"/></linearGradient>')
    w, body = pill('trial', 'Trial', defs, 'url(#b)', 'rgba(214,220,232,.30)', '#F2F3F5', extra=OVL)
    out['trial'] = svg(w, H, 'Trial', defs, body)
    # Pro
    defs = ('<radialGradient id="g" cx="0" cy="0" r="1.2" gradientUnits="objectBoundingBox"><stop offset="0" stop-color="#7896FF" stop-opacity=".28"/><stop offset=".55" stop-color="#7896FF" stop-opacity="0"/></radialGradient>'
            '<linearGradient id="b" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#0B1B3F"/><stop offset=".55" stop-color="#14306B"/><stop offset="1" stop-color="#0E2350"/></linearGradient>')
    w, body = pill('pro', 'Pro', defs, 'url(#b)', 'rgba(150,175,255,.40)', '#F3F6FF', extra=OVL)
    out['pro'] = svg(w, H, 'Pro', defs, body)
    # Founding Member: gold foil pill + dark medallion with the gold compass
    defs = ('<linearGradient id="b" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#F3DB93"/><stop offset=".3" stop-color="#D9B45A"/><stop offset=".52" stop-color="#F7E7B5"/><stop offset=".74" stop-color="#C99A3E"/><stop offset="1" stop-color="#E9CC7E"/></linearGradient>'
            '<radialGradient id="hl" cx="0" cy="0" r="1.2" gradientUnits="objectBoundingBox"><stop offset="0" stop-color="#FFFAE6" stop-opacity=".95"/><stop offset=".55" stop-color="#FFFAE6" stop-opacity="0"/></radialGradient>'
            '<radialGradient id="m" cx=".5" cy=".36" r=".7"><stop offset="0" stop-color="#37260C" stop-opacity=".9"/><stop offset=".58" stop-color="#120A04" stop-opacity=".95"/><stop offset="1" stop-color="#080502"/></radialGradient>'
            '<linearGradient id="fg" x1="5" y1="3" x2="19" y2="21" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#F6E3A6"/><stop offset=".45" stop-color="#D4AE52"/><stop offset="1" stop-color="#9C7424"/></linearGradient>')
    med = (f'<circle cx="{4+9}" cy="{H/2}" r="9" fill="url(#m)" stroke="#140C04" stroke-opacity=".5"/>' + compass(13 - 6, H/2 - 6, 12, 'url(#fg)'))
    w, body = pill('founding', 'Founding Member', defs, 'url(#b)', 'rgba(120,86,20,.45)', '#24190A', lead=med, lead_w=18, extra=lambda w: f'<rect x="1" y="1" width="{w-2:.2f}" height="{H-2}" rx="{R-1}" fill="url(#hl)"/>')
    out['founding-member'] = svg(w, H, 'Founding Member', defs, body)
    # ATO seats: the landing's ink plan card (.plan-main) + gold ATO seal
    for n in (2, 5):
        defs = seal_defs('a')
        lead = seal('#F5B83D', '#fff', 'a', 5, 5, 16)
        w, body = pill(f'ato{n}', f'ATO · {n} seats', defs, '#141413', 'rgba(255,255,255,.14)', '#FAF9F5', lead=lead, lead_w=16)
        out[f'ato-{n}-seat'] = svg(w, H, f'ATO {n} seats', defs, body)
    # Seals
    defs = seal_defs('a'); out['ato-verified'] = svg(24, 24, 'Verified ATO', defs, seal('#F5B83D', '#fff', 'a', 0, 0, 24))
    defs = seal_defs('d'); out['dfe-verified'] = svg(24, 24, 'Verified DFE', defs, seal('#1D9BF0', '#fff', 'd', 0, 0, 24))
    # Founding medallion alone (r3 dark medallion + gold compass) and the compass
    defs = ('<radialGradient id="m" cx=".5" cy=".36" r=".7"><stop offset="0" stop-color="#37260C" stop-opacity=".9"/><stop offset=".58" stop-color="#120A04" stop-opacity=".95"/><stop offset="1" stop-color="#080502"/></radialGradient>'
            '<linearGradient id="fg" x1="5" y1="3" x2="19" y2="21" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#F6E3A6"/><stop offset=".45" stop-color="#D4AE52"/><stop offset="1" stop-color="#9C7424"/></linearGradient>')
    out['founding-medallion'] = svg(44, 44, 'Founding Member medallion', defs,
        '<circle cx="22" cy="22" r="21.5" fill="url(#m)" stroke="#140C04" stroke-opacity=".5"/>' + compass(10, 10, 24, 'url(#fg)'))
    return out

# ---------- monochrome / print-safe: black on white, tier shown by shape not colour ----------
def mono():
    out = {}
    K = '#111'
    def mpill(label, style, lead=None, lead_w=0):
        padL = 10 if not lead else 4 + lead_w + 7
        d, tw = text_path(label.upper(), SZ, TR, padL, H / 2); w = padL + tw + 11
        if style == 'hair':   rect = f'<rect x=".5" y=".5" width="{w-1:.2f}" height="{H-1}" rx="{R-.5}" fill="#fff" stroke="{K}" stroke-width="1"/>'; tc = K
        if style == 'dash':   rect = f'<rect x=".5" y=".5" width="{w-1:.2f}" height="{H-1}" rx="{R-.5}" fill="#fff" stroke="{K}" stroke-width="1" stroke-dasharray="3 2.2"/>'; tc = K
        if style == 'solid':  rect = f'<rect x=".5" y=".5" width="{w-1:.2f}" height="{H-1}" rx="{R-.5}" fill="{K}" stroke="{K}" stroke-width="1"/>'; tc = '#fff'
        if style == 'double': rect = (f'<rect x=".5" y=".5" width="{w-1:.2f}" height="{H-1}" rx="{R-.5}" fill="{K}" stroke="{K}" stroke-width="1"/>'
                                      f'<rect x="2.5" y="2.5" width="{w-5:.2f}" height="{H-5}" rx="{R-2.5}" fill="none" stroke="#fff" stroke-width=".8"/>'); tc = '#fff'
        return w, rect + (lead or '') + f'<path d="{d}" fill="{tc}"/>'
    for key, label, style in [('free', 'Free', 'hair'), ('trial', 'Trial', 'dash'), ('pro', 'Pro', 'solid')]:
        w, b = mpill(label, style); out[key] = svg(w, H, label, '', b)
    lead = (f'<circle cx="13" cy="{H/2}" r="9" fill="#fff"/>' + compass(7, H/2 - 6, 12, K))
    w, b = mpill('Founding Member', 'double', lead=lead, lead_w=18); out['founding-member'] = svg(w, H, 'Founding Member', '', b)
    for n in (2, 5):
        lead = seal('', '', '', 5, 5, 16, mono='outline').replace('fill="#fff" stroke="#111"', 'fill="#fff" stroke="#fff"').replace('<path d="%s" fill="#111"/>' % SEAL[4], '<path d="%s" fill="#111"/>' % SEAL[4])
        w, b = mpill(f'ATO · {n} seats', 'solid', lead=lead, lead_w=16); out[f'ato-{n}-seat'] = svg(w, H, f'ATO {n} seats', '', b)
    out['ato-verified'] = svg(24, 24, 'Verified ATO', '', seal('', '', '', 0, 0, 24, mono='solid'))
    out['dfe-verified'] = svg(24, 24, 'Verified DFE', '', seal('', '', '', 0, 0, 24, mono='outline'))
    out['founding-medallion'] = svg(44, 44, 'Founding Member medallion', '', f'<circle cx="22" cy="22" r="21.25" fill="{K}"/><circle cx="22" cy="22" r="18.5" fill="none" stroke="#fff" stroke-width=".8"/>' + compass(10, 10, 24, '#fff'))
    return out

if __name__ == '__main__':
    def uniq(k, v):
        ids = set(re.findall(r'id="([A-Za-z0-9]+)"', v)); ids.discard(None)
        for i in ids:
            v = v.replace(f'id="{i}"', f'id="{k}-{i}"').replace(f'url(#{i})', f'url(#{k}-{i})')
        return v
    for k, v in colour().items(): open(os.path.join(HERE, f'badge-{k}.svg'), 'w').write(uniq(k, v))
    for k, v in mono().items(): open(os.path.join(HERE, f'badge-{k}-mono.svg'), 'w').write(v)
    print(sorted(os.listdir(HERE)))
