"""Site-style desktop + mobile SVG for #binary-polyhedral-fields.
Light palette matches the rest of the page; dark twins are made by dark_figs."""
import json, math, html
from pathlib import Path
HERE = Path(__file__).resolve().parent
FIG = HERE.parent / 'figures'
O = json.loads((HERE / 'measure-2O-results.json').read_text())
I = json.loads((HERE / 'measure-2I-results.json').read_text())
BG='#faf8f2'; INK='#233d36'; GREEN='#3f7763'; GOLD='#b28b4e'; MUTED='#65746c'
GRID='#dce2d8'; PUR='#7a5c8f'; BLUE='#3f6f8f'; GRAY='#9aa59f'; RUST='#a8553a'
B2O=0.14871260537428388
B2I=0.06976505974012515
SUP='⁰¹²³⁴⁵⁶⁷⁸⁹'
def p10(e):
    if e==0: return '1'
    s=''.join(SUP[int(d)] for d in str(abs(e)))
    return '10'+('⁻' if e<0 else '')+s

def make(mobile=False):
    W, Ht = (400, 1480) if mobile else (1240, 640)
    a = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {Ht}" role="img" aria-labelledby="title desc">',
         '<title id="title">Field-level check of the barrier exponent for the 48-element and 120-element groups</title>',
         '<desc id="desc">Three panels. Left: log of the completed Model A norm for a binary octahedral field, against log of 2 sigma minus 1, approaching slope 0.1487. Middle: log of the two 2-dimensional L-functions of that field; one has a simple forced zero at one half (slope 1), the other is finite and nonzero. Right: the same Model A measurement for a binary icosahedral field, approaching slope 0.0698.</desc>',
         f'<rect width="{W}" height="{Ht}" fill="{BG}"/>',
         f'<style>text{{fill:{INK};font-family:Georgia,serif}}.sans{{font-family:Arial,sans-serif}}.muted{{fill:{MUTED}}}</style>']
    def text(x, y, s, size=16, cl='', anchor='start', fill=None):
        a.append(f'<text x="{x:.1f}" y="{y:.1f}" font-size="{size}" class="{cl}" text-anchor="{anchor}"'+(f' style="fill:{fill}"' if fill else '')+'>'+html.escape(s)+'</text>')
    def line(x1, y1, x2, y2, color=GRID, dash=None, w=1):
        a.append(f'<path d="M{x1:.2f},{y1:.2f}L{x2:.2f},{y2:.2f}" stroke="{color}" stroke-width="{w}" fill="none"'+(f' stroke-dasharray="{dash}"' if dash else '')+'/>')
    def poly(pts, color, w=2.2, dash=None):
        a.append('<path d="M'+'L'.join(f'{x:.1f},{y:.1f}' for x,y in pts)+f'" stroke="{color}" stroke-width="{w}" fill="none"'+(f' stroke-dasharray="{dash}"' if dash else '')+'/>')
    def dot(x, y, col):
        a.append(f'<circle cx="{x:.1f}" cy="{y:.1f}" r="4" fill="{col}" stroke="{BG}" stroke-width="1"/>')
    if mobile:
        text(20, 28, 'FIELD CHECK · 2O AND 2I', 11, 'sans muted')
        text(20, 56, 'Actual Frobenius, measured slope', 20)
        PA=(50, W-24, 150, 400); PB=(50, W-24, 540, 800); PC=(50, W-24, 980, 1240)
    else:
        text(36, 32, 'FIELD-LEVEL CHECK  ·  BINARY OCTAHEDRAL 2O  AND  BINARY ICOSAHEDRAL 2I', 12, 'sans muted')
        text(36, 70, 'Actual Frobenius classes, measured against the predicted slope', 24)
        text(1204, 70, '[project, float numerics]', 13, 'sans muted', 'end')
        PA=(70, 390, 150, 470); PB=(470, 800, 150, 470); PC=(890, 1210, 150, 470)

    def panel_barrier(box, data, pred, title, series, ylab, note_lines):
        L,R,T,B=box
        # collect y range from series + reference
        pts_all=[]
        plotted={}
        for key,col,lab in series:
            vals=data['barrier'][key]['values']
            pts=[(math.log10(2*v['eps']), v['log_nrd_E_completed']) for v in vals]
            plotted[key]=(pts,col,lab)
            pts_all.extend(pts)
        xs=[p[0] for p in pts_all]; ys=[p[1] for p in pts_all]
        # include a reference segment of length ~2 in log10
        X0,X1=min(xs)-0.15, max(xs)+0.15
        # y pad
        ypad=0.18*(max(ys)-min(ys) or 1)
        Y0,Y1=min(ys)-ypad, max(ys)+ypad
        xx=lambda l: L+(l-X0)/(X1-X0)*(R-L)
        yy=lambda v: B-(v-Y0)/(Y1-Y0)*(B-T)
        # grid at integer log10 of 2σ-1
        lo=math.ceil(X0-1e-9); hi=math.floor(X1+1e-9)
        for e in range(lo, hi+1):
            line(xx(e), T, xx(e), B)
            # 10^{e} label; e is log10(2σ-1), typically -3,-2,-1,0? 2*1e-1=0.2 → -0.7; 2e-4 → -3.7
            text(xx(e), B+16, p10(e), 10, 'sans muted', 'middle')
        # horizontal-ish none; a few y ticks
        for i in range(5):
            v=Y0+i*(Y1-Y0)/4
            line(L, yy(v), R, yy(v))
            text(L-8, yy(v)+4, f'{v:.1f}', 10, 'sans muted', 'end')
        text((L+R)/2, B+36, '2σ − 1  (log scale)  →', 11, 'sans muted', 'middle')
        text(L-8, T-22, title, 13, 'sans')
        for key,col,lab in series:
            pts,col,_=plotted[key]
            pix=[(xx(x),yy(y)) for x,y in pts]
            poly(pix, col, 1.8)
            for p in pix: dot(*p, col)
        # reference slope through last point of the first series
        key0=series[0][0]
        pts=plotted[key0][0]
        xL,yL=pts[-1]
        def yref(x): return yL + pred*(x-xL)*math.log(10)
        poly([(xx(X0+0.05), yy(yref(X0+0.05))), (xx(X1-0.05), yy(yref(X1-0.05)))], INK, 1.2, '3 4')
        # legend
        ly=T+16
        for key,col,lab in series:
            line(L+8, ly, L+28, ly, col, None, 2.2)
            text(L+34, ly+4, lab, 11, 'sans muted'); ly+=16
        line(L+8, ly, L+28, ly, INK, '3 4', 1.6)
        text(L+34, ly+4, f'predicted slope {pred:.4f}', 11, 'sans muted')
        for j,s in enumerate(note_lines):
            text(L, B+54+14*j, s, 11, 'sans muted')

    # (a) 2O barrier
    panel_barrier(PA, O, B2O, '(a) 2O  ·  log of the completed Model A norm',
                  (('11.3', GREEN, 'height 11.3, last slope 0.1509'),
                   ('23.5', BLUE, 'height 23.5, last slope 0.1538')),
                  '', [] if not mobile else [])
    # (b) 2O L(ρ)
    L,R,T,B = PB
    cm=O['central_rho_rootno_minus']; cp=O['central_rho_rootno_plus']
    def series_L(rec):
        return list(zip([math.log10(e) for e in rec['eps']], rec['log_abs']))
    sminus, splus = series_L(cm), series_L(cp)
    xs=[x for x,_ in sminus+splus]; ys=[y for _,y in sminus+splus]
    X0,X1=min(xs)-0.2, max(xs)+0.2
    ypad=0.12*(max(ys)-min(ys))
    Y0,Y1=min(ys)-ypad, max(ys)+ypad
    xx=lambda l: L+(l-X0)/(X1-X0)*(R-L)
    yy=lambda v: B-(v-Y0)/(Y1-Y0)*(B-T)
    for e in range(int(math.ceil(X0)), int(math.floor(X1))+1):
        line(xx(e), T, xx(e), B)
        text(xx(e), B+16, p10(e), 10, 'sans muted', 'middle')
    for i in range(5):
        v=Y0+i*(Y1-Y0)/4
        line(L, yy(v), R, yy(v)); text(L-8, yy(v)+4, f'{v:.0f}', 10, 'sans muted', 'end')
    text((L+R)/2, B+36, 'σ − ½  (log scale)  →', 11, 'sans muted', 'middle')
    text(L-8, T-22, '(b) 2O  ·  log |L(ρ, ½+ε)|', 13, 'sans')
    pix=[(xx(x),yy(y)) for x,y in sminus]
    poly(pix, RUST, 1.8)
    for p in pix: dot(*p, RUST)
    pix=[(xx(x),yy(y)) for x,y in splus]
    poly(pix, PUR, 1.8)
    for p in pix: dot(*p, PUR)
    # slope 1 through last minus point
    xL,yL=sminus[-1]
    def y1(x): return yL + 1.0*(x-xL)*math.log(10)
    poly([(xx(X0+0.1),yy(y1(X0+0.1))), (xx(X1-0.1),yy(y1(X1-0.1)))], INK, 1.2, '3 4')
    ly=T+16
    for col,lab in ((RUST, 'ρ, root number −1, slope → 1'),
                    (PUR, 'ρ ⊗ ε, L(½) ≈ 4.735, slope → 0'),
                    (INK, 'slope 1 (a simple zero)')):
        line(L+8, ly, L+28, ly, col, '3 4' if col==INK else None, 2.0 if col!=INK else 1.6)
        text(L+34, ly+4, lab, 11, 'sans muted'); ly+=16

    # (c) 2I barrier
    panel_barrier(PC, I, B2I, '(c) 2I  ·  log of the completed Model A norm',
                  (('23.5', BLUE, 'height 23.5, last slope 0.0688'),
                   ('11.3', GREEN, 'height 11.3, last slope 0.0730'),
                   ('0.0', GOLD, 'height 0, last slope 0.0708')),
                  '', [])
    cap = (('(a) For a totally real 2O-field (Galois group [48,28], not GL(2,3)), the completed Model A norm shrinks like (2σ − 1)^0.1509 in the last decade at height 11.3, against the predicted 0.1487. (b) One of the two',
            '2-dimensional L-functions has a simple forced zero at ½ (PARI slopes → 1); its sign-twist is finite and nonzero there. (c) For a totally real 2I-field the last-decade slopes are 0.0688, 0.0730 and 0.0708 against 0.0698. Floats; primes to 20 000. No RH claim.')
           if not mobile else
           ('(a) 2O field, last-decade slope 0.1509 at height 11.3, against 0.1487.',
            '(b) 2O: L(ρ) has a simple forced zero at ½; the twist does not vanish.',
            '(c) 2I field, last-decade slopes 0.0688, 0.0730, 0.0708 against 0.0698.',
            'Floats; primes to 20 000. No RH claim.'))
    y0 = (PC[3] if mobile else PA[3]) + (70 if mobile else 108)
    for j,s in enumerate(cap):
        text(20 if mobile else 36, y0+16*j, s, 11 if mobile else 12, 'sans muted')
    a.append('</svg>')
    return '\n'.join(a)

FIG.mkdir(exist_ok=True)
for m in (False, True):
    path=FIG/f'polyhedral-fields-site{"-mobile" if m else ""}.svg'
    path.write_text(make(m))
    print('wrote', path)
