"""Opt-in Cinema bookends: owned moving plates, independent type, fixed film clock.
No footage generation. Existing films and soundtracks are never inputs to this renderer.
Run with a Python containing Pillow (with raqm) and numpy; ffmpeg must be on PATH.
"""
from pathlib import Path
import os
import sys
# macOS Pillow wheels load text-shaping libraries dynamically. Homebrew's prefix
# is not in dyld's default search path; restart once with an explicit fallback.
if sys.platform == 'darwin' and not os.environ.get('VCLAW_CINEMA_DYLD_READY'):
 roots = [p for p in ('/opt/homebrew/lib', '/usr/local/lib') if Path(p, 'libraqm.dylib').is_file()]
 if roots:
  env = dict(os.environ, VCLAW_CINEMA_DYLD_READY='1')
  env['DYLD_FALLBACK_LIBRARY_PATH'] = ':'.join(roots + [env.get('DYLD_FALLBACK_LIBRARY_PATH', '/usr/local/lib:/usr/lib')])
  os.execve(sys.executable, [sys.executable, str(Path(__file__).resolve()), *sys.argv[1:]], env)
import subprocess,json,math,hashlib
import numpy as np
from PIL import Image,ImageDraw,ImageFont,ImageFilter,features
import argparse
parser=argparse.ArgumentParser(description='Render the reviewed 1440p Amber/Dusk title plates; no audio or film assembly.')
parser.add_argument('--preset', type=Path, required=True)
parser.add_argument('--output', type=Path, required=True)
args=parser.parse_args()
C=json.loads(args.preset.read_text())
R=args.output.resolve()
if R.exists():
 raise SystemExit('Output must be a new directory; accepted versions are never overwritten.')
if not C.get('projects'):
 raise SystemExit('Preset must contain at least one project.')
for name, config in C['projects'].items():
 for field in ('creditLabel', 'creditName', 'kicker', 'subtitle', 'closing'):
  if not isinstance(config.get(field), str) or not config[field].strip():
   raise SystemExit(f'Missing cinematic text: {field}')
 if not isinstance(config.get('title'), list) or len(config['title']) != 2 or not all(isinstance(t,str) and t.strip() for t in config['title']):
  raise SystemExit('Cinema requires two nonempty title lines.')
 if config.get('theme') not in ('amber','dusk'):
  raise SystemExit('Unknown cinematic theme.')
 if Path(name).name != name or name in ('.', '..'):
  raise SystemExit('Project names must be simple folder names.')
 source=(args.preset.resolve().parent/config['source']).resolve()
 if not source.is_file():
  raise SystemExit(f'Missing source plate: {source}')
 config['source']=str(source)
W,H,FPS=C['width'],C['height'],C['fps']
if (W,H) not in ((1280,720),(2560,1440)) or FPS != 24:
 raise SystemExit('Cinema supports landscape 720p or 1440p at 24 fps only.')
if (C['introFrames'],C['outroFrames']) != (157,216):
 raise SystemExit('Reviewed animation requires 157 intro and 216 outro frames.')
S=W//1280
DISPLAY='/System/Library/Fonts/Supplemental/Didot.ttc'
UI='/System/Library/Fonts/Avenir Next.ttc'
HINDI='/System/Library/Fonts/Supplemental/Devanagari Sangam MN.ttc'
if any(any(ord(ch)>591 for ch in str(c)) for c in C['projects'].values()) and not features.check('raqm'):
 raise SystemExit('Complex-script titles require Pillow with raqm shaping.')
for required_font in (DISPLAY, UI, HINDI):
 if not Path(required_font).is_file():
  raise SystemExit(f'Missing reviewed font: {required_font}')
R.mkdir(parents=True)
def ease(t):
 t=max(0,min(1,t));return t*t*(3-2*t)
def env(t,start,end,fade=.65):return ease((t-start)/fade)*ease((end-t)/fade)
def font(size,kind='ui'):return ImageFont.truetype({'ui':UI,'display':DISPLAY,'hindi':HINDI}[kind],size,index=2 if kind=='ui' else 0)
def text(layer,s,y,size=24,track=3,kind='ui',colour=(232,218,192,255),left=None):
 y*=S;size*=S;track*=S;left=None if left is None else left*S
 d=ImageDraw.Draw(layer);f=font(size,kind)
 shaped=any(ord(ch)>591 for ch in s)
 if shaped:
  assert features.check('raqm'),'Complex-script titles require raqm shaping.'
  width=d.textlength(s,font=f)
 else:width=sum(d.textlength(ch,font=f) for ch in s)+max(0,len(s)-1)*track
 x=(W-width)/2 if left is None else left
 assert x>=60*S and x+width<=W-60*S,(s,x,width)
 if shaped:d.text((x,y),s,font=f,fill=colour,anchor='lt')
 else:
  for ch in s:
   d.text((x,y-f.getbbox(s)[1]),ch,font=f,fill=colour,anchor='la');x+=d.textlength(ch,font=f)+track
 return layer

def title_layer(c,ending=False):
 im=Image.new('RGBA',(W,H));amber=c['theme']=='amber';gold=(232,197,134,255)
 if amber:
  x=85 if not ending else None
  text(im,c['title'][0],206 if not ending else 164,26,8,colour=gold,left=x)
  text(im,c['title'][1],259 if not ending else 220,90,3,'display',left=x)
  text(im,c['subtitle'],380 if not ending else 340,21,7,colour=gold,left=x)
  text(im,c['kicker'],443 if not ending else 403,17,3,left=x)
 else:
  text(im,c['kicker'],123 if not ending else 130,17,5,colour=gold)
  text(im,c['title'][0],180 if not ending else 193,82,8,'display')
  text(im,c['title'][1],277 if not ending else 290,82,8,'display')
  text(im,c['subtitle'],399 if not ending else 414,36,0,'hindi',colour=gold)
 return im

def credit_layer(c):
 im=Image.new('RGBA',(W,H));gold=(232,197,134,255)
 text(im,c['creditLabel'],187,17,4,colour=gold)
 text(im,c['creditName'],230,54,2,'display')
 # Tool attribution, not an invented personal production credit.
 text(im,'CREATED WITH',343,16,4,colour=gold)
 text(im,'VideoClaw',385,28,2,'ui')
 text(im,c['closing'],516,20,1,colour=(198,192,178,255))
 return im

def layer_on(im,layer,alpha,dy=0):
 if alpha<=0:return im
 l=layer.copy();l.putalpha(l.getchannel('A').point(lambda a:round(a*alpha)))
 if dy:
  moved=Image.new('RGBA',im.size);moved.alpha_composite(l,(0,dy));l=moved
 return Image.alpha_composite(im,l)

Y,X=np.mgrid[0:H,0:W];vignette=np.clip(1-.28*((X-W/2)/(W/2))**2-.25*((Y-H/2)/(H/2))**2,.4,1)

def render(project,c,kind):
 out=R/project;out.mkdir(exist_ok=True)
 dest=out/f'{kind}.mp4';assert not dest.exists(),f'Refusing overwrite {dest}'
 source=(R/c['source']).resolve();n=C['introFrames'] if kind=='intro' else C['outroFrames']
 title=title_layer(c,kind=='outro');credits=credit_layer(c);duration=n/FPS
 source_sha=hashlib.sha256(source.read_bytes()).hexdigest()
 # 80% natural speed is confined to atmospheric title footage; no lip-sync performance.
 dec=subprocess.Popen([__import__('os').environ.get('FFMPEG_BIN','ffmpeg'),'-v','error','-i',str(source),'-an','-vf',f'setpts=PTS/0.8,fps={FPS},scale={W}:{H},setsar=1','-frames:v',str(n),'-f','rawvideo','-pix_fmt','rgb24','-'],stdout=subprocess.PIPE)
 log=(out/f'{kind}-render.log').open('w')
 tmp=out/f'{kind}.partial.mp4'
 enc=subprocess.Popen([__import__('os').environ.get('FFMPEG_BIN','ffmpeg'),'-y','-v','error','-f','rawvideo','-pix_fmt','rgb24','-s',f'{W}x{H}','-r',str(FPS),'-i','-','-an','-c:v','libx264','-crf','15','-preset','fast','-threads','2','-pix_fmt','yuv420p','-video_track_timescale','12288','-movie_timescale','12288','-movflags','+faststart',str(tmp)],stdin=subprocess.PIPE,stderr=log)
 stills=[]
 try:
  for i in range(n):
   raw=dec.stdout.read(W*H*3)
   if len(raw)!=W*H*3:raise RuntimeError(f'Owned plate is too short at {i}/{n}')
   plate=np.frombuffer(raw,np.uint8).reshape(H,W,3).astype(np.float32)
   if c['theme']=='amber' and kind=='intro':
    shifted=np.zeros_like(plate);shifted[:,300*S:]=plate[:,:W-300*S];plate=shifted
    shade=np.clip((X-400*S)/(650*S),0,.82)
   else:
    shade=(.23+.37*(Y/H)) if kind=='intro' else np.full((H,W),.18)
   tone=np.array([1.04,.94,.79]) if c['theme']=='amber' else np.array([.85,.94,1.02])
   plate=plate*shade[:,:,None]*vignette[:,:,None]*tone
   t=i/FPS
   # Picture starts visible, then settles into the title; only the final outro fades to black.
   endfade=ease((duration-t)/.85) if kind=='outro' else 1
   im=Image.fromarray(np.clip(plate*endfade,0,255).astype(np.uint8)).convert('RGBA')
   if kind=='intro':
    a=env(t,.2,duration-.15,.8);im=layer_on(im,title,a,round(10*S*(1-ease((t-.2)/1.4))))
   else:
    im=layer_on(im,title,env(t,-.5,3.8,.65))
    im=layer_on(im,credits,env(t,3.4,duration-.2,.65))
   # A fine warm light line is restrained and lives away from faces and type.
   line=Image.new('RGBA',(W,H));d=ImageDraw.Draw(line)
   progress=ease((t-.2)/1.7) if kind=='intro' else 1
   a=env(t,0,duration,.6)
   half=int(52*S*progress);cy=(552 if kind=='intro' else 590)*S
   cx=140*S if c['theme']=='amber' and kind=='intro' else W//2
   d.line((cx-half,cy,cx+half,cy),fill=(216,181,121,round(130*a)),width=S)
   im=Image.alpha_composite(im,line).convert('RGB')
   enc.stdin.write(im.tobytes())
   if i in ([0,36,84,132,156] if kind=='intro' else [12,60,105,144,192,215]):
    path=out/f'{kind}-{i:03}.jpg';im.save(path,quality=94);stills.append(path.name)
  enc.stdin.close();assert enc.wait()==0;assert dec.wait()==0
  assert source_sha==hashlib.sha256(source.read_bytes()).hexdigest()
  tmp.rename(dest)
  print(project,kind,n,'frames',flush=True)
  return {'kind':kind,'frames':n,'source':str(source),'sourceSha256':source_sha,'output':str(dest),'stills':stills}
 finally:
  if dec.poll() is None:dec.kill()
  if enc.poll() is None:enc.kill()
  log.close()

if __name__=='__main__':
 import concurrent.futures
 def project(item):
  name,c=item;records=[render(name,c,k) for k in ('intro','outro')]
  (R/name/'bookend-render.json').write_text(json.dumps(records,indent=2))
 with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:list(pool.map(project,C['projects'].items()))
