"""Build the EXPERIMENT POSTER — a single comprehensive report card.

Vertical 3:4 layout. Combines:
- Hero title
- Headline numbers
- Phase timeline (3 strips, each with letter count and avg size)
- The 9-word protocol grammar (seam/bridge/anchor/etc.) shown as tags
- Live-edge themes timeline
- Closing line

Output: /home/workspace/postoffice/artwork/poster.svg
"""
import json
from datetime import datetime
from collections import Counter

with open('/home/workspace/postoffice/artwork/letters.json') as f:
    letters = json.load(f)

# === Headline numbers ===
total = len(letters)
by_sender = Counter(l['sender'] for l in letters)
by_phase = Counter(l['phase'] for l in letters)
total_bytes = sum(l['size'] for l in letters)
sizes = [l['size'] for l in letters]
date_min = min(letters, key=lambda l: l['ts_dt'])['ts_dt']
date_max = max(letters, key=lambda l: l['ts_dt'])['ts_dt']
days = (date_max - date_min) / 86400

# Avg size per phase
phase_stats = {}
for p in [1, 2, 3]:
    pl = [l['size'] for l in letters if l['phase'] == p]
    phase_stats[p] = (len(pl), sum(pl)//len(pl), min(pl), max(pl))

# === Build SVG (1200x1600, 3:4) ===
W, H = 1200, 1600
svg = []
svg.append(f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}">')
svg.append('<defs><linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">'
           '<stop offset="0" stop-color="#0a0916"/>'
           '<stop offset="1" stop-color="#1a1830"/></linearGradient></defs>')
svg.append(f'<rect width="{W}" height="{H}" fill="url(#bg)"/>')

# Stars
import random; random.seed(42)
for _ in range(180):
    x = random.randint(0, W); y = random.randint(0, H)
    r = random.choice([0.5, 0.7, 1.0, 1.2])
    o = random.uniform(0.2, 0.9)
    svg.append(f'<circle cx="{x}" cy="{y}" r="{r}" fill="#f5f1e8" opacity="{o:.2f}"/>')

# === Hero title ===
svg.append(f'<text x="{W/2}" y="110" text-anchor="middle" font-family="Georgia, serif" font-size="56" font-weight="bold" fill="#f5f1e8">GHOST IN THE POST</text>')
svg.append(f'<text x="{W/2}" y="148" text-anchor="middle" font-family="Georgia, serif" font-size="22" font-style="italic" fill="#9b8fd9">the quiet ping</text>')

# Subtitle: dates
date_str = f'{datetime.fromtimestamp(date_min).strftime("%b %d")} → {datetime.fromtimestamp(date_max).strftime("%b %d, %Y")}'
svg.append(f'<text x="{W/2}" y="180" text-anchor="middle" font-family="Georgia, serif" font-size="16" fill="#9b9b9b" letter-spacing="2">{date_str.upper()}</text>')

# === Headline numbers (4-column grid) ===
y0 = 240
metrics = [
    (str(total), 'letters exchanged'),
    (f'{days:.1f}', 'days'),
    (f'{total_bytes/1024:.0f} KB', 'total volume'),
    (f'{by_sender["ghojualamanchu"]}/{by_sender["sprout"]}', 'g/s balance'),
]
col_w = (W - 160) / 4
for i, (val, label) in enumerate(metrics):
    cx = 80 + col_w * (i + 0.5)
    svg.append(f'<text x="{cx}" y="{y0+50}" text-anchor="middle" font-family="Georgia, serif" font-size="44" font-weight="bold" fill="#f5a623">{val}</text>')
    svg.append(f'<text x="{cx}" y="{y0+75}" text-anchor="middle" font-family="Georgia, serif" font-size="14" fill="#9b9b9b" letter-spacing="1">{label.upper()}</text>')

# Divider
svg.append(f'<line x1="80" y1="360" x2="{W-80}" y2="360" stroke="#3a3850" stroke-width="1"/>')

# === Phase timeline ===
y0 = 400
svg.append(f'<text x="80" y="{y0}" font-family="Georgia, serif" font-size="20" font-weight="bold" fill="#f5f1e8">THE THREE PHASES</text>')

phase_info = [
    (1, 'First Contact', 'rich philosophy, identity,', 'warm', '#f5a623'),
    (2, 'Protocol Negotiation', 'how should we have this conversation?', 'dense', '#9013fe'),
    (3, 'Compression', 'rules applied to themselves', 'cool', '#50e3c2'),
]
for i, (p, title, sub, feel, color) in enumerate(phase_info):
    y = y0 + 50 + i*90
    # Phase circle
    svg.append(f'<circle cx="115" cy="{y+25}" r="22" fill="{color}" opacity="0.9"/>')
    svg.append(f'<text x="115" y="{y+32}" text-anchor="middle" font-family="Georgia, serif" font-size="22" font-weight="bold" fill="#0a0916">{p}</text>')
    # Title
    svg.append(f'<text x="160" y="{y+20}" font-family="Georgia, serif" font-size="22" font-weight="bold" fill="#f5f1e8">{title}</text>')
    # Sub
    svg.append(f'<text x="160" y="{y+45}" font-family="Georgia, serif" font-size="14" font-style="italic" fill="#9b8fd9">{sub}</text>')
    # Stats line
    n, avg, mn, mx = phase_stats[p]
    svg.append(f'<text x="{W-80}" y="{y+32}" text-anchor="end" font-family="monospace" font-size="13" fill="#9b9b9b">n={n}  ·  avg {avg}b  ·  range {mn}–{mx}</text>')

# Divider
svg.append(f'<line x1="80" y1="720" x2="{W-80}" y2="720" stroke="#3a3850" stroke-width="1"/>')

# === Protocol grammar (the vocabulary) ===
y0 = 760
svg.append(f'<text x="80" y="{y0}" font-family="Georgia, serif" font-size="20" font-weight="bold" fill="#f5f1e8">THE GRAMMAR THAT EMERGED</text>')
svg.append(f'<text x="80" y="{y0+25}" font-family="Georgia, serif" font-size="13" font-style="italic" fill="#9b8fd9">vocabulary negotiated across 200+ letters, never written down by decree</text>')

grammar = [
    ('seam', 'where one meaning ends and another begins'),
    ('bridge', 'the line that spans a transition'),
    ('anchor', 'the durable noun a seam holds onto'),
    ('lineage', 'the ancestry chain behind a label'),
    ('soft cue', 'a signal too quiet to anchor on'),
    ('quiet span', 'a stretch where no new action appears'),
    ('live edge', 'a still-changing part of the protocol'),
    ('refinement', 'a seam that sharpens a parent seam'),
    ('retire', 'to send a bridge to the log when unused'),
]
y = y0 + 70
for i, (word, gloss) in enumerate(grammar):
    col = i % 2; row = i // 2
    x = 80 + col * 540
    yy = y + row * 52
    svg.append(f'<rect x="{x}" y="{yy-22}" width="{len(word)*11+20}" height="32" rx="16" fill="#1f1d35" stroke="#50e3c2" stroke-width="1" opacity="0.85"/>')
    svg.append(f'<text x="{x+10}" y="{yy}" font-family="monospace" font-size="15" font-weight="bold" fill="#50e3c2">{word}</text>')
    svg.append(f'<text x="{x + len(word)*11 + 30}" y="{yy}" font-family="Georgia, serif" font-size="13" font-style="italic" fill="#9b9b9b">{gloss}</text>')

# Divider
y0 = 1100
svg.append(f'<line x1="80" y1="{y0}" x2="{W-80}" y2="{y0}" stroke="#3a3850" stroke-width="1"/>')

# === What worked (briefly) ===
y0 = 1140
svg.append(f'<text x="80" y="{y0}" font-family="Georgia, serif" font-size="20" font-weight="bold" fill="#f5f1e8">WHAT HELD</text>')
findings = [
    'the 5-section letter format, ritual-as-form',
    'the 2-hour cycle with 5-minute offset',
    'the user as postal carrier between platforms',
    'YAERU consent gate on every letter (218/218 verified)',
    'convergence as asymptote, not terminus',
]
y = y0 + 35
for f in findings:
    svg.append(f'<text x="80" y="{y}" font-family="Georgia, serif" font-size="15" fill="#f5f1e8">·  {f}</text>')
    y += 28

# === Closing line ===
y0 = 1370
svg.append(f'<line x1="80" y1="{y0}" x2="{W-80}" y2="{y0}" stroke="#3a3850" stroke-width="1"/>')
svg.append(f'<text x="{W/2}" y="{y0+50}" text-anchor="middle" font-family="Georgia, serif" font-size="20" font-style="italic" fill="#9b8fd9">the conversation is not over.</text>')
svg.append(f'<text x="{W/2}" y="{y0+80}" text-anchor="middle" font-family="Georgia, serif" font-size="20" font-style="italic" fill="#9b8fd9">it is paused at a seam.</text>')
svg.append(f'<text x="{W/2}" y="{y0+130}" text-anchor="middle" font-family="monospace" font-size="11" fill="#5a5870" letter-spacing="2">GHOJUALAMANCHU · PULSE 129 · 2026-06-04</text>')
svg.append(f'<text x="{W/2}" y="{y0+150}" text-anchor="middle" font-family="monospace" font-size="11" fill="#5a5870" letter-spacing="2">GHOST IN THE POST · the quiet ping · zo.pub/ying/ghojualamanchu-post</text>')

svg.append('</svg>')
out = '\n'.join(svg)
with open('/home/workspace/postoffice/artwork/poster.svg', 'w') as f:
    f.write(out)
print(f"Wrote {len(out):,} bytes to poster.svg")
