"""Record saved M01 complex FEM fields as a scientific 3D movie. No solver run.

python render_m01.py --input M01_web.json --output NEW_DIRECTORY
Requires numpy, Pillow, matplotlib (fonts only), imageio-ffmpeg==0.6.0.
Output refuses replacement. The gain affects geometry only, not field values.
"""
import argparse,csv,hashlib,json,math,sys
from pathlib import Path
import numpy as np
from PIL import Image,ImageDraw,ImageFont
from matplotlib import font_manager
import imageio_ffmpeg

def sha(path): return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def peak_vector(a,b):
    aa=np.sum(a*a,axis=-1);bb=np.sum(b*b,axis=-1);ab=np.sum(a*b,axis=-1)
    return np.sqrt((aa+bb+np.hypot(aa-bb,2*ab))/2)
def palette(t):
    stops=np.array([[35,67,98],[56,132,145],[171,217,170],[247,211,123]])
    t=np.clip(t,0,1)*3;k=np.minimum(2,t.astype(int));f=t-k
    return stops[k]*(1-f[...,None])+stops[k+1]*f[...,None]

def main():
    ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('--input',type=Path,required=True);ap.add_argument('--output',type=Path,required=True);args=ap.parse_args()
    args.output.mkdir(parents=True,exist_ok=False)
    source_hash=sha(args.input);data=json.loads(args.input.read_text(encoding='utf8'));g=data['geometry'];L=g['side_m'];nodes=np.asarray(g['nodes_m']);faces=np.asarray(g['surface_triangles']);materials=data['materials']
    assert len(materials)==3 and math.isclose(L,.02)
    prepared=[]
    for m in materials:
        u=m['forced'];a=np.asarray(u['displacement_real_m']);b=np.asarray(u['displacement_imag_m']);assert a.shape==nodes.shape==b.shape
        assert np.all(a[g['fixed_node_ids']]==0) and np.all(b[g['fixed_node_ids']]==0)
        prepared.append((m,a,b))
    max_u=max(float(peak_vector(a,b).max()) for m,a,b in prepared);gain=.05*L/max_u
    font_path=font_manager.findfont('DejaVu Sans');mono_path=font_manager.findfont('DejaVu Sans Mono')
    fonts={n:ImageFont.truetype(font_path,n) for n in [14,16,18,22,38]};mono=ImageFont.truetype(mono_path,13)
    width,height,fps,frames=1280,720,24,180
    az,el=-.75,.4;eye=np.array([math.cos(el)*math.cos(az),math.cos(el)*math.sin(az),math.sin(el)]);right=np.array([-math.sin(az),math.cos(az),0]);up=np.cross(eye,right);rotation=np.stack([right,up,eye],axis=1);scale=225/(L*1.55)
    colors_bg=(9,18,13);white=(234,242,233);muted=(170,192,175);green=(179,227,195)
    corners=np.array([[0,0,0],[L,0,0],[L,L,0],[0,L,0],[0,0,L],[L,0,L],[L,L,L],[0,L,L]])
    edges=[[0,1],[1,2],[2,3],[3,0],[4,5],[5,6],[6,7],[7,4],[0,4],[1,5],[2,6],[3,7]]
    names={'structural_steel':'Structural steel','aluminum_6061':'Aluminum 6061','fused_silica_hpfs7980':'HPFS fused silica'}
    def image_at(theta):
        im=Image.new('RGB',(width,height),colors_bg);d=ImageDraw.Draw(im)
        d.text((42,24),'ASHLEY KALKOWSKI  /  DESTROYING BOULDERS  /  M01',font=mono,fill=green)
        d.text((40,57),'Three materials. One test.',font=fonts[38],fill=white)
        d.text((42,113),'20 mm solid cube · fixed bottom · 1 N peak harmonic top-face traction',font=fonts[18],fill=muted)
        d.text((42,145),f'Saved 48-mode FEM response · phase replay slowed to 0.4 Hz · motion enlarged {gain:,.0f}×',font=fonts[16],fill=(234,201,151))
        peaks=[]
        for j,(m,a,b) in enumerate(prepared):
            x0=38+j*414;cx=x0+187;cy=395
            d.rounded_rectangle((x0,191,x0+394,596),radius=10,fill=(16,31,22),outline=(48,74,55),width=1)
            d.text((x0+18,210),names.get(m['id'],m['id']),font=fonts[22],fill=white)
            f=m['forced']['frequency_hz'];d.text((x0+18,246),f'{f/1000:.3f} kHz · selected grid peak',font=fonts[14],fill=green)
            u=a*math.cos(theta)-b*math.sin(theta);p=nodes+gain*u
            pr=(p-L/2)@rotation;pr[:,0]=cx+scale*pr[:,0];pr[:,1]=cy-scale*pr[:,1]
            tri=pr[faces];raw=p[faces];n=np.cross(raw[:,1]-raw[:,0],raw[:,2]-raw[:,0]);n/=np.maximum(np.linalg.norm(n,axis=1)[:,None],1e-30)
            shade=.55+.45*np.maximum(0,n@np.array([.2,-.4,.89]));mag=np.linalg.norm(u,axis=1);face_mag=mag[faces].mean(axis=1)
            col=np.clip(palette(face_mag/max_u)*shade[:,None],0,255).astype('uint8')
            for idx in np.argsort(tri[:,:,2].mean(axis=1)):
                xy=[tuple(q[:2]) for q in tri[idx]];d.polygon(xy,fill=tuple(col[idx]));d.line(xy+[xy[0]],fill=(26,50,40),width=1)
            cp=(corners-L/2)@rotation;cp[:,0]=cx+scale*cp[:,0];cp[:,1]=cy-scale*cp[:,1]
            for s,e in edges:d.line([tuple(cp[s,:2]),tuple(cp[e,:2])],fill=(137,160,143),width=1)
            peaks.append(float(mag.max()));period_t=theta/(2*math.pi*f)
            d.text((x0+18,508),f'Phase {(theta*180/math.pi)%360:05.1f}°  |  t = {period_t*1e6:.3f} µs',font=mono,fill=muted)
            d.text((x0+18,538),f'Max node motion now: {mag.max()*1e6:.5f} µm',font=fonts[14],fill=white)
            d.text((x0+18,565),f'E {m["E_pa"]/1e9:g} GPa   ρ {m["rho_kg_m3"]:g} kg/m³   ν {m["nu"]:g}',font=fonts[14],fill=muted)
        d.text((42,617),'INSTANTANEOUS DISPLACEMENT MAGNITUDE  /  SHARED COLOR SCALE',font=mono,fill=muted)
        for x in range(360):d.line([(42+x,643),(42+x,654)],fill=tuple(palette(np.asarray(x/359)).astype('uint8')),width=1)
        d.text((42,662),'0',font=fonts[14],fill=muted);d.text((280,662),f'{max_u*1e6:.5f} µm',font=fonts[14],fill=muted)
        d.text((474,643),'LINEAR ELASTICITY · NO CRACK LAW · 0 PHYSICAL TESTS',font=fonts[16],fill=white)
        d.text((474,665),'MESH / MODAL ACCURACY NOT RESOLVED',font=fonts[14],fill=(234,201,151))
        d.text((474,690),'ashleykalkowski.com/destroying-boulders/materials',font=mono,fill=muted)
        return im,peaks
    video=args.output/'M01-material-phase-replay.mp4'
    writer=imageio_ffmpeg.write_frames(str(video),(width,height),fps=fps,codec='libx264',quality=5.3,pix_fmt_in='rgb24',pix_fmt_out='yuv420p',macro_block_size=16,output_params=['-preset','slow','-movflags','+faststart','-metadata','title=M01 saved finite-element phase replay'])
    writer.send(None);ledger=[]
    try:
        for i in range(frames):
            theta=2*math.pi*i/(fps*2.5);im,peaks=image_at(theta);writer.send(im.tobytes())
            row={'frame':i,'video_time_s':i/fps,'phase_radians':theta,'visual_gain':gain}
            for j,(m,a,b) in enumerate(prepared):row[m['id']+'_physical_time_s']=theta/(2*math.pi*m['forced']['frequency_hz']);row[m['id']+'_max_node_displacement_m']=peaks[j]
            ledger.append(row)
            if i in [15,30,45,60]:im.save(args.output/f'frame-{i:03d}.png')
        poster,_=image_at(math.pi/2);poster.save(args.output/'M01-poster.png')
    finally:writer.close()
    with (args.output/'FRAME-MAP.csv').open('w',newline='',encoding='utf8') as f:w=csv.DictWriter(f,fieldnames=list(ledger[0]));w.writeheader();w.writerows(ledger)
    assert sha(args.input)==source_hash
    report={'schema':'M01-numerical-recording-1','source_sha256':source_hash,'source_filename':args.input.name,'render_source_sha256':sha(__file__),'frame_count':frames,'width':width,'height':height,'fps':fps,'duration_s':frames/fps,'playback_phase_hz':.4,'physical_frequency_by_material':{m['id']:m['forced']['frequency_hz'] for m,a,b in prepared},'visual_gain_common':gain,'physical_displacement_scale_max_m':max_u,'motion_equation':'u(theta)=U_real*cos(theta)-U_imag*sin(theta)','color':'Instantaneous physical displacement vector magnitude; triangle average, shared scale. Directional shading changes apparent brightness.','geometry':'Saved FEM volume boundary faces; same linear field, not a manufactured object or fracture render.','convention':'Each material has its own simulated frequency and physical phase time; same displayed phase does not mean equal physical elapsed time.','numerical_status':'Retained model approximation; inspect convergence and direct-reference screens.','physical_tests':0,'new_physics_solves':0,'source_unchanged':True,'dependencies':{'python':sys.version.split()[0],'numpy':np.__version__,'imageio_ffmpeg':imageio_ffmpeg.__version__},'outputs':{p.name:{'bytes':p.stat().st_size,'sha256':sha(p)} for p in sorted(args.output.iterdir()) if p.is_file()}}
    (args.output/'RENDER-RECEIPT.json').write_text(json.dumps(report,indent=2)+'\n',encoding='utf8');print(json.dumps({'video':str(video),'bytes':video.stat().st_size,'frames':frames,'gain':gain,'source_unchanged':True}))
if __name__=='__main__':main()
