"""Generate six chalk panels from the archived experiment plus wood and stone textures."""
from pathlib import Path
import math,json,io
from matplotlib.mathtext import math_to_image
from matplotlib.font_manager import FontProperties
import numpy as np
from PIL import Image, ImageFont, ImageDraw, ImageFilter
R=Path(__file__).resolve().parents[1]; A=R/'scene/assets'; A.mkdir(exist_ok=True)
rng=np.random.default_rng(1859)
font_dir=Path('/System/Library/Fonts/Supplemental')
def face(sz,kind='chalk'):
    name={'chalk':'ChalkboardSE.ttc','math':'Georgia Italic.ttf','head':'Baskerville.ttc','mono':'Courier New.ttf'}[kind]
    if (font_dir/name).exists():return ImageFont.truetype(str(font_dir/name),sz)
    return ImageFont.truetype('DejaVuSans.ttf',sz)
def noise(w,h,sw,sh):
    return np.array(Image.fromarray(rng.integers(0,255,(sh,sw),dtype=np.uint8)).resize((w,h),Image.Resampling.BICUBIC)).astype(float)/255-.5
def texture(base,v):return Image.fromarray(np.uint8(np.clip(np.array(base)[None,None,:]+v[:,:,None],0,255)))
W,H=960,402
titles=['The critical strip','The zeta function','Where the zeros lie','How primes accumulate','Reading the proof','Checking the claim']
tags=['ζ(s) = 0','ζ(s) ↔ ζ(1−s)','Z(t) ∈ ℝ','ψ(x) = Σ Λ(n)','(M) implies RH¹','5 Lean targets']
subtitle=['0 < Re(s) < 1','Continuation in s','Hardy’s real function','n ≤ x, prime powers','¹with character estimates','three used axioms']
side=[['σ = ½','Re(s) = 1/2','nontrivial zeros'],['Re(s) > 1','ζ(s) = ∏ (1−p⁻ˢ)⁻¹','product over primes'],['γ₁ ≈ 14.1347','N*(T) = #{γₙ ≤ T}','finite indexed list'],['π(10⁶) = 78,498','Li(x) = Ei(log x)','exact sieve'],['13 hypotheses','weighted sum (M)','two character bounds'],['propext','Classical.choice','Quot.sound']]
Z=np.genfromtxt(R/'results/zeros.csv',delimiter=',',names=True);C=np.genfromtxt(R/'results/critical_line.csv',delimiter=',',names=True)
P=np.genfromtxt(R/'results/primes.csv',delimiter=',',names=True);g=np.load(R/'results/field.npz')
for j in range(6):
    tex=texture([38,62,55],noise(W,H,12,6)*11+noise(W,H,200,70)*3+rng.normal(0,2.4,(H,W))).convert('RGB')
    d=ImageDraw.Draw(tex);paper='#e5e4cf'; gold='#dec58c'; blue='#a6d4d0'
    def txt(x,y,s,size,color=paper,kind='chalk'):d.text((x,y),s,font=face(size,kind),fill=color,stroke_width=0)
    txt(32,13,'0'+str(j+1),24,gold,'mono');txt(96,7,titles[j],51);d.line((36,78,924,77),fill='#a4b7a2',width=2)
    def formula(x,y,tex,height,col):
        buf=io.BytesIO();math_to_image('$'+tex+'$',buf,prop=FontProperties(size=26),dpi=120,format='png',color='black')
        img=Image.open(buf).convert('RGB');mask=Image.fromarray(255-np.asarray(img)[:,:,0]);bounds=mask.getbbox()
        if bounds:mask=mask.crop(bounds)
        scale=height/mask.height;mask=mask.resize((round(mask.width*scale),height),Image.Resampling.LANCZOS)
        teximg=Image.new('RGB',mask.size,col);globals()['tex'].paste(teximg,(x,y),mask)
    headlines=[r'\zeta(s)=0',r'\xi(s)=\xi(1-s)',r'Z(t)\in\mathbb{R}',r'\psi(x)=\sum_{n\leq x}\Lambda(n)',r'(M)\ \Longrightarrow\ {\rm RH}^{*}',r'5\ {\rm Lean\ targets}']
    formula(40,95,headlines[j],42,gold)
    txt(40,157,subtitle[j].replace('¹with','* with'),23)
    eqs=[[r'\sigma=\frac{1}{2}',r's=\sigma+it'],[r'\mathrm{Re}(s)>1',r'\zeta(s)=\prod_p(1-p^{-s})^{-1}'],[r'\gamma_1\approx14.1347',r'N_*(T)=\#\{\gamma_n\leq T\}'],[r'\pi(10^6)=78{,}498',r'\mathrm{Li}(x)=\mathrm{Ei}(\log x)']]
    if j<4:
        formula(44,219,eqs[j][0],31,blue);formula(44,272,eqs[j][1],30,paper);txt(44,323,side[j][2],23)
    else:
        for i,s in enumerate(side[j]):txt(44,215+i*42,s,25,blue if i==0 else paper)
    x0,y0,x1,y1=479,110,915,339
    def path(xx,yy,clr=paper,span=None):
        xx=np.asarray(xx);yy=np.asarray(yy);lo,hi=span if span else (yy.min(),yy.max())
        pts=list(zip(x0+(xx-xx.min())/(xx.max()-xx.min())*(x1-x0),y1-(yy-lo)/(hi-lo)*(y1-y0)));d.line(pts,fill=clr,width=3)
    def axes(xlabel,ylabel):
        d.line((x0,y0,x0,y1,x1,y1),fill='#bacab5',width=2);txt(x1-66,y1+2,xlabel,19);txt(x0+6,y0-18,ylabel,18)
    if j==0:
        axes('Re s','Im s');x=(x0+x1)//2;d.line((x,y0,x,y1),fill=gold,width=2)
        for t in Z['height'][:8]:
            h=y1-t/46*(y1-y0);d.ellipse((x-6,h-5,x+6,h+5),fill=paper)
        txt(x-18,y1+3,'½',23,gold)
    if j==1:
        axes('t','ζ(½+it)');mask=C['t']<33;path(C['t'][mask],C['real'][mask],blue,(-3.6,4.2));path(C['t'][mask],C['imaginary'][mask],gold,(-3.6,4.2))
    if j==2:
        axes('t','Z(t)');mask=C['t']<33;path(C['t'][mask],C['Hardy_Z'][mask],paper,(-3.8,3.8));d.line((x0,(y0+y1)/2,x1,(y0+y1)/2),fill=gold,width=2)
    if j==3:
        axes('x','π(x)');q=P[P['x']<=80];xx=q['x'];yy=q['pi'];path(np.repeat(xx,2)[1:],np.repeat(yy,2)[:-1],gold)
    if j==4:
        for x,y,s in [(510,123,'13 inputs'),(705,123,'(M)'),(509,239,'2 bounds'),(775,270,'RH')]:txt(x,y,s,28,blue)
        for points in [[610,145,682,145],[744,161,793,248],[646,258,757,281]]:d.line(points,fill=gold,width=3)
    if j==5:
        for i,s in enumerate(['statement matched','axioms audited','kernel replay¹']):d.line((508,139+i*62,516,148+i*62,535,123+i*62),fill=gold,width=3);txt(545,118+i*62,s.replace('¹','*'),26,blue)
        txt(508,317,'* external logs',20,gold)
    arr=np.array(tex).astype(float);arr+=rng.normal(0,3,(H,W,1));pepper=rng.random((H,W))<.065;arr[pepper]*=.73
    Image.fromarray(np.uint8(np.clip(arr,0,255))).save(A/f'board{j+1}.jpg',quality=92)
# Seamless-enough long-grain oak and mineral floor finish, for classroom furniture.
w,h=768,384;y,x=np.indices((h,w))
grain=np.sin(y*.62+3*np.sin(x/178)+7*noise(w,h,8,9))*4+noise(w,h,8,130)*24+noise(w,h,28,48)*9+rng.normal(0,1.6,(h,w))
texture([156,112,76],grain).save(A/'oak.jpg',quality=90)
texture([173,166,149],noise(w,h,22,20)*9+rng.normal(0,5,(h,w))).save(A/'stone.jpg',quality=86)

