#!/usr/bin/env python3
"""Builds brand/badges: SVG files, the visual page (index.html) and BADGES.md. Run from anywhere: python3 brand/badges/src/build.py"""
import os, re, html, json, sys
HERE = os.path.dirname(os.path.abspath(__file__)); ROOT = os.path.dirname(HERE); sys.path.insert(0, HERE)
import marks, data
from data import THEMES, THEME_NAME, TOK
E = html.escape
def w(rel, s):
    p = os.path.join(ROOT, rel); os.makedirs(os.path.dirname(p), exist_ok=True); open(p, 'w').write(s)
SLUG = {'a': 'a-climb-out', 'b': 'b-split-plan', 'c': 'c-nose-in'}
# ---------- files ----------
for k in 'abc':
    w(f'founding-jet/svg/founding-jet-{SLUG[k]}.svg', marks.medallion(k) + '\n')
    w(f'founding-jet/svg/founding-jet-{SLUG[k]}-mono-dark.svg', marks.medallion(k, uid=f'md{k}', mono='dark') + '\n')
    w(f'founding-jet/svg/founding-jet-{SLUG[k]}-mono-light.svg', marks.medallion(k, uid=f'ml{k}', mono='light') + '\n')
    w(f'founding-jet/svg/pass-watermark-{SLUG[k]}.svg', marks.watermark(k, '#5A3F0A') + '\n')
w('founding-jet/svg/founding-jet-small-mark.svg', marks.small_mark() + '\n')
w('founding-jet/svg/vision-jet-side.svg', marks.jet_master('side') + '\n')
w('founding-jet/svg/vision-jet-plan.svg', marks.jet_master('plan') + '\n')
w('founding-jet/svg/vision-jet-side-gold.svg', marks.jet_gold_side() + '\n')
for k in ['current', 'a', 'b', 'c']:
    nm = {'current': 'current', 'a': 'a-hairline-seal', 'b': 'b-enamel', 'c': 'c-liquid-glass'}[k]
    for t in THEMES: w(f'tick/svg/tick-{nm}-{t}.svg', marks.tick(k, t) + '\n')

def inline(svg, cls='', label=None):
    """Inline an SVG with unique ids, sized by CSS."""
    global _n; _n += 1; u = f'u{_n}_'
    svg = re.sub(r'id="([^"]+)"', lambda m: f'id="{u}{m.group(1)}"', svg)
    svg = re.sub(r'url\(#([^)]+)\)', lambda m: f'url(#{u}{m.group(1)})', svg)
    i = svg.index('>'); svg = re.sub(r'\swidth="\d+" height="\d+"', '', svg[:i], count=1) + svg[i:]
    if cls: svg = svg.replace('<svg ', f'<svg class="{cls}" ', 1)
    return svg
_n = 0
LOCK = {n: open(os.path.join(ROOT, 'existing/locked-9nov', n + '.svg')).read() for n in ['ato-tick-locked', 'dfe-tick-locked', 'founding-compass-gold']}

# ---------- page ----------
def tokens_css():
    out = []
    for t in THEMES:
        v = TOK[t]; out.append(f'[data-t={t}]{{' + ';'.join(f'--{k}:{x}' for k, x in v.items()) + f';color-scheme:{"dark" if t in ("midnight","amethyst") else "light"}}}')
    return '\n'.join(out)

def tick_tile(t):
    rows = ''
    for k in ['current', 'a', 'b', 'c']:
        m = marks.TICK[k]
        sizes = ''.join(f'<span class="sz s{s}">{inline(marks.tick(k, t))}<i>{s}</i></span>' for s in (112, 48, 24, 16))
        rows += f'<div class="tk-row"><b class="tk-name">{"" if k=="current" else k.upper()+" · "}{E(m["name"])}</b><div class="tk-sizes">{sizes}</div></div>'
    return f'<div class="tile" data-t="{t}"><p class="tile-h">{THEME_NAME[t]}</p>{rows}</div>'

def success_screen(t, k):
    return (f'<div class="succ" data-t="{t}"><div class="succ-ic">{inline(marks.tick(k, t))}</div>'
            f'<p class="succ-t">Account created.</p><p class="succ-l">Welcome to Go Around.</p></div>')

def name_row(mark_svg, name='Thandi Mokoena', pill='CPL', sfx=''):
    return (f'<span class="nrow"><span class="nm">{E(name)}{f"<span class=sfx>{sfx}</span>" if sfx else ""}</span>{mark_svg}'
            f'<span class="lic">{pill}</span><span class="stars" aria-label="Rated 5 of 5">★★★★★</span></span>')

def pass_card(kind):
    """Gold Founding pass from sign-up v12 (signup-hookup.css .pass7.founding). kind: current | a | b | c"""
    if kind == 'current':
        bg = '<div class="rwy" aria-hidden="true"></div>'
        seal = f'<div class="seal" aria-hidden="true">{inline(LOCK["founding-compass-gold"], "seal-c")}</div>'
        nmk = inline(LOCK['founding-compass-gold'], 'mk18')
    else:
        bg = f'<div class="jetwm" aria-hidden="true">{inline(marks.watermark(kind))}</div>'
        seal = f'<div class="seal" aria-hidden="true">{inline(LOCK["founding-compass-gold"], "seal-c")}</div>'
        nmk = inline(LOCK['founding-compass-gold'], 'mk18')
    return (f'<section class="pass founding" aria-label="Founding pass, {"current runway" if kind=="current" else "option "+kind.upper()}">{bg}{seal}'
            f'<div class="lbl">Go Around · Founding pass</div>'
            f'<div class="row1"><div class="av" aria-hidden="true">TM</div><div class="who"><div class="pname">Thandi Mokoena{nmk}</div><div class="handle">@thandi.flies</div></div></div>'
            f'<div class="chips"><span class="chip main"><i></i>CPL (A)</span><span class="chip"><i></i>Night</span><span class="chip"><i></i>IR</span></div>'
            f'<div class="fmark">Founding Member</div></section>')

def jet_tile(t):
    meds = ''.join(f'<div class="jt-col"><div class="jt-sizes">' + ''.join(f'<span class="sz s{s}"><img src="founding-jet/svg/founding-jet-{SLUG[k]}.svg" alt="" width="{s}" height="{s}"><i>{s}</i></span>' for s in (96, 48, 24, 16)) +
                   f'</div><p class="jt-cap">{k.upper()} · {E(marks.COMP[k]["name"])}</p></div>' for k in 'abc')
    small = (f'<div class="jt-col"><div class="jt-sizes">' + ''.join(f'<span class="sz s{s}">{inline(marks.small_mark())}<i>{s}</i></span>' for s in (24, 18, 16, 14)) +
             '</div><p class="jt-cap">Small mark, for names</p></div>')
    row = name_row(inline(marks.small_mark(), 'mk15'))
    tag = f'<span class="ftag"><span class="ftag-ic"><img class="mk16" src="founding-jet/svg/founding-jet-b-split-plan.svg" alt="" width="16" height="16"></span>Founding Member</span>'
    return f'<div class="tile" data-t="{t}"><p class="tile-h">{THEME_NAME[t]}</p><div class="jt-grid">{meds}{small}</div><div class="jt-use">{row}{tag}</div></div>'

ST = {'locked': 'Locked', 'live': 'In use', 'draft': 'Draft', 'missing': 'Missing', 'question': 'Ask MT'}
def inv_rows():
    out = ''
    for b in data.INVENTORY:
        ic = f'<img src="{b["file"]}" alt="">' if b['file'] else '<span class="noic">Aa</span>'
        out += (f'<article class="inv"><div class="inv-ic">{ic}</div><div class="inv-b"><h3>{E(b["name"])} <span class="st {b["status"]}">{ST[b["status"]]}</span></h3>'
                f'<p>{E(b["meaning"])}</p><dl><dt>Where</dt><dd>{E(b["where"])}</dd><dt>Colour</dt><dd>{E(b["colour"])}</dd><dt>Source</dt><dd class="mono">{E(b["src"])}</dd></dl></div></article>')
    return out

def sys_tile(t):
    ato = inline(LOCK['ato-tick-locked'], 'mk15'); dfe = inline(LOCK['dfe-tick-locked'], 'mk15'); fc = inline(LOCK['founding-compass-gold'], 'mk15')
    rows = [
      ('Review, DFE', name_row(dfe, 'Sipho Ndlovu', 'ATPL', '.dfe')),
      ('Review, Founding', name_row(fc, 'Thandi Mokoena', 'CPL')),
      ('Review, Pro or Free', name_row('', 'Ayesha Patel', 'PPL')),
      ('Reply, paying school', f'<span class="nrow"><span class="nm">capeflight<span class="sfx">.official</span></span>{ato}</span>'),
      ('Anonymous', '<span class="nrow"><span class="nm">Anonymous</span></span>'),
      ('School tags (proposed)', '<span class="nrow"><span class="tag warn">Expired</span><span class="tag">DTO</span><span class="tag">Drone</span></span>'),
    ]
    return f'<div class="tile" data-t="{t}"><p class="tile-h">{THEME_NAME[t]}</p>' + ''.join(f'<div class="sy-row"><span class="sy-k">{k}</span>{v}</div>' for k, v in rows) + '</div>'

CSS = open(os.path.join(HERE, 'page.css')).read().replace('/*TOKENS*/', tokens_css())
tick_tiles = ''.join(tick_tile(t) for t in THEMES)
succ = ''.join(f'<figure class="sfig"><figcaption>{"Current" if k=="current" else k.upper()+" · "+marks.TICK[k]["name"]}</figcaption><div class="sgrid">' + ''.join(success_screen(t, k) for t in THEMES) + '</div></figure>' for k in ['current', 'a', 'b', 'c'])
opts = ''.join(f'<figure class="opt"><div class="opt-m">{inline(marks.medallion(k))}</div><figcaption><b>{k.upper()} · {E(marks.COMP[k]["name"])}</b><span>{E(marks.COMP[k]["note"])}</span></figcaption></figure>' for k in 'abc')
passes = ''.join(f'<figure class="pfig"><figcaption>{"Today: the runway" if k=="current" else k.upper()+" · "+marks.COMP[k]["name"]}</figcaption>{pass_card(k)}</figure>' for k in ['current', 'a', 'b', 'c'])
jet_tiles = ''.join(jet_tile(t) for t in THEMES)
sys_tiles = ''.join(sys_tile(t) for t in THEMES)
surf = ''.join(f'<li><b>{E(a)}</b><span>{E(b)}</span></li>' for a, b in data.SURFACES)
rules = ''.join(f'<li><b>{E(a)}</b><span>{E(b)}</span></li>' for a, b in data.RULES)
dos = ''.join(f'<li>{E(x)}</li>' for x in data.DOS); donts = ''.join(f'<li>{E(x)}</li>' for x in data.DONTS)
qs = ''.join(f'<li>{E(x)}</li>' for x in data.QUESTIONS)
masters = f'<div class="masters"><figure>{inline(marks.jet_master("side","currentColor"))}<figcaption>Side view</figcaption></figure><figure>{inline(marks.jet_master("plan","currentColor"))}<figcaption>Plan view</figcaption></figure></div>'
themebtn = ''.join(f'<button type="button" class="tb" data-set="{t}" aria-pressed="{"true" if t=="pearl" else "false"}">{THEME_NAME[t]}</button>' for t in THEMES)

PAGE = f'''<!doctype html><html lang="en-ZA" data-t="pearl"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="robots" content="noindex"><title>Badges · Go Around · draft 20 Nov 2026</title><style>{CSS}</style></head>
<body><header class="top"><div class="wrap top-in"><p class="brand">Go Around <span>Badges</span></p><div class="tbar" role="group" aria-label="Theme">{themebtn}</div></div></header>
<main class="wrap">
<section class="hero"><p class="eyebrow"><span class="draft">Draft</span> for MT to agree · 20 Nov 2026</p><h1>Badges: the green tick, the Founding jet and one set of rules</h1>
<p class="lede">Three things you asked for: an honest look at the green tick, half a Vision Jet instead of the runway on the Founding pass, and how every badge is used. Every picture below is the real file at its real size, in all four themes.</p>
<nav class="toc" aria-label="On this page"><a href="#tick">1 · Green tick</a><a href="#jet">2 · Founding jet</a><a href="#system">3 · Badge rules</a><a href="#files">Files</a><a href="#questions">Questions</a></nav></section>

<section id="tick" class="sec"><h2>1 · The green tick</h2>
<div class="verdict"><p class="v-k">Verdict</p><p class="v-t">Good, but not fancy yet.</p>
<p>The draw-in motion is lovely and the shape is clean. What holds it back is the colour and the glow: a bright mint green with a soft blurred halo, plus a green wash over the whole page. It reads like a payment app, not like Go Around. It is also the only bright green in the whole set, and a third tick colour next to the gold ATO tick and the blue DFE tick.</p>
<p>My pick is <b>B · Enamel</b>. It is made the same way as the verified seals, it stays clear at 16 px, and it says "done" without shouting. <b>C · Liquid glass</b> is the most iOS 26, and best on Midnight and Amethyst. <b>A · Hairline seal</b> is the quietest.</p></div>
<h3 class="h3">At real sizes, all four themes</h3><p class="sub">112 px is the success screen. 48, 24 and 16 px show how it holds up small.</p>
<div class="tiles">{tick_tiles}</div>
<h3 class="h3">On the success screen</h3><div class="sfigs">{succ}</div>
<ul class="notes">{''.join(f'<li><b>{"Current" if k=="current" else k.upper()+" · "+E(marks.TICK[k]["name"])}</b>: {E(marks.TICK[k]["note"])}</li>' for k in ['current','a','b','c'])}</ul></section>

<section id="jet" class="sec"><h2>2 · Founding Member: half a Vision Jet</h2>
<p class="lede">The runway lines on the gold Founding pass become half a Cirrus SF50 Vision Jet. Round 2: I built the jet as a small 3D model on a grid, traced from public photos of N124MW (9.4 m long, 11.8 m span), then shaded it in our gold. What makes it a Vision Jet: the V-tail at about 40°, the single engine sitting on top of the rear fuselage and running into the tail, the big wraparound windscreen, three large cabin windows, a cabin that is taller at the front, and a straight tapered wing with no winglets whose trailing edge sweeps forward at the root. Three ways to cut it in half:</p>
<div class="opts">{opts}</div>
<h3 class="h3">On the gold pass</h3><p class="sub">The gold pass from sign-up v12. Only the runway changes; the locked compass stays in the seal and after the name. The jet seals above can take the compass&#8217;s place if you want.</p><div class="pfigs">{passes}</div>
<h3 class="h3">Sizes, all four themes</h3><p class="sub">The half-jet seals are made for 48 px and up (the pass seal is 58 px). At 24 px they still read as a gold jet; at 16 px they do not, so names use the small mark: the whole jet from above.</p>
<div class="tiles">{jet_tiles}</div>
<h3 class="h3">The jet drawing</h3><p class="sub">Side and plan views straight from the same 3D model. In flight the gear is up, so the nose gear is not drawn; the CAPS parachute hatch sits flush behind the cabin and is too fine to show at seal size.</p>{masters}</section>

<section id="system" class="sec"><h2>3 · Badge rules <span class="draft">Draft</span></h2>
<p class="lede">Every badge we have, where it goes, and the rules that keep it classy. Nothing here changes the live site until you agree.</p>
<h3 class="h3">The rules</h3><ul class="rules">{rules}</ul>
<h3 class="h3">How a row looks, all four themes</h3><div class="tiles">{sys_tiles}</div>
<h3 class="h3">Where badges appear</h3><ul class="rules">{surf}</ul>
<h3 class="h3">Every badge</h3><div class="invs">{inv_rows()}</div>
<div class="dd"><div><h3 class="h3">Do</h3><ul class="dl do">{dos}</ul></div><div><h3 class="h3">Don't</h3><ul class="dl dont">{donts}</ul></div></div></section>

<section id="files" class="sec"><h2>Files</h2><ul class="files">
<li><a href="BADGES.md">BADGES.md</a>, the written rules</li>
<li><a href="https://github.com/sdzrxwfxd2-cloud/go-around-design/tree/design/one-home-20nov/brand/badges/founding-jet/svg/">founding-jet/svg/</a>: the three seals in colour and mono, the pass watermarks, the small mark and the jet drawings</li>
<li><a href="https://github.com/sdzrxwfxd2-cloud/go-around-design/tree/design/one-home-20nov/brand/badges/founding-jet/png-8k/">founding-jet/png-8k/</a> and <a href="https://github.com/sdzrxwfxd2-cloud/go-around-design/tree/design/one-home-20nov/brand/badges/founding-jet/png-4k/">png-4k/</a>: 8192 and 4096 px PNGs, transparent</li>
<li><a href="https://github.com/sdzrxwfxd2-cloud/go-around-design/tree/design/one-home-20nov/brand/badges/tick/svg/">tick/svg/</a>: the current tick and A, B, C in each theme</li>
<li><a href="https://github.com/sdzrxwfxd2-cloud/go-around-design/tree/design/one-home-20nov/brand/badges/existing/">existing/</a>: copies of the locked 9 Nov badges for reference</li></ul></section>

<section id="questions" class="sec"><h2>Questions for MT</h2><ol class="qs">{qs}</ol></section>
</main><footer class="wrap foot">Go Around · brand/badges · go-around-design, branch design/one-home-20nov · draft, 20 Nov 2026 (SAST)</footer>
<script>(()=>{{const h=document.documentElement,b=[...document.querySelectorAll('.tb')];const set=t=>{{h.dataset.t=t;b.forEach(x=>x.setAttribute('aria-pressed',String(x.dataset.set===t)));try{{localStorage.setItem('ga-badges-t',t)}}catch(e){{}}}};
b.forEach(x=>x.addEventListener('click',()=>set(x.dataset.set)));const q=new URLSearchParams(location.search).get('t');let s=null;try{{s=localStorage.getItem('ga-badges-t')}}catch(e){{}}set(q||s||'pearl')}})();</script>
</body></html>'''
w('index.html', PAGE)

# ---------- BADGES.md ----------
md = ['# Go Around badges: how we use them', '', '**DRAFT for MT to agree, 20 Nov 2026 (SAST).** Nothing here changes the live site until MT says yes.', '',
      'Visual version: [index.html](index.html), preview https://badges-20nov.go-around-design-previews.pages.dev/', '', '## The rules', '']
md += [f'- **{a}.** {b}' for a, b in data.RULES]
md += ['', '## Where badges appear', '', '| Surface | What shows |', '|---|---|'] + [f'| {a} | {b} |' for a, b in data.SURFACES]
md += ['', '## Every badge', '', '| Badge | Status | Meaning | Where | Colour | Source |', '|---|---|---|---|---|---|']
md += [f'| {b["name"]}{f" ([svg]({b["file"]}))" if b["file"] else ""} | {ST[b["status"]]} | {b["meaning"]} | {b["where"]} | {b["colour"]} | `{b["src"]}` |' for b in data.INVENTORY]
md += ['', '## Colours per theme', '', '| Token | ' + ' | '.join(THEME_NAME[t] for t in THEMES) + ' |', '|---|' + '---|' * 4]
for k, lab in [('tx2', 'Licence pill text'), ('gl2', 'Licence pill fill'), ('sfx', '.official / .dfe'), ('goldTx', 'Gold text'), ('warn', 'Warning tag (Expired, Pending)'), ('ok', 'Success green (text)')]:
    md.append(f'| {lab} | ' + ' | '.join(f'`{TOK[t][k]}`' for t in THEMES) + ' |')
md += ['| ATO tick | `#F5B83D` in every theme | | | |', '| DFE tick | `#1D9BF0` in every theme | | | |', '| Founding gold | `#F6E3A6` to `#9C7424` in every theme | | | |']
md += ['', '## Do', ''] + [f'- {x}' for x in data.DOS] + ['', "## Don't", ''] + [f'- {x}' for x in data.DONTS]
md += ['', '## 1. The green tick', '', '**Verdict: good, but not fancy yet.** The draw-in motion and the shape are clean. The bright mint green, the blurred halo and the green wash over the whole page make it read like a payment app, and it is a third tick colour next to the gold ATO and blue DFE ticks.', '',
       'Three refined versions with the same meaning (done), compared at 112, 48, 24 and 16 px in all four themes on the visual page:', '']
md += [f'- **{"Current" if k=="current" else k.upper()+" · "+marks.TICK[k]["name"]}**: {marks.TICK[k]["note"]}' for k in ['current', 'a', 'b', 'c']]
md += ['', 'Recommendation: **B · Enamel**. Files: `tick/svg/tick-<version>-<theme>.svg`.', '',
       '## 2. Founding Member: half a Vision Jet', '', 'The runway lines on the gold Founding pass are replaced by half a Cirrus SF50 Vision Jet, drawn from scratch for Go Around (V-tail, single engine on top of the rear fuselage, low wing, rounded nose; proportions checked against public photos on Wikimedia Commons, nothing traced or copied).', '']
md += [f'- **{k.upper()} · {marks.COMP[k]["name"]}**: {marks.COMP[k]["note"]} `founding-jet/svg/founding-jet-{SLUG[k]}.svg`' for k in 'abc']
md += ['', 'Each comes in colour, mono dark and mono light, plus a pass watermark (`pass-watermark-*.svg`) and 8K / 4K PNGs. Below 24 px use `founding-jet-small-mark.svg` (the whole jet from above): a half jet does not read at 16 px.', '',
       '## Questions for MT', ''] + [f'{i}. {q}' for i, q in enumerate(data.QUESTIONS, 1)]
w('BADGES.md', '\n'.join(md) + '\n')
print('built', _n, 'inline svgs')
