# Local Windows rebuild of the Song for Zula end-frame board.
# Port of the claude.ai build.py: reads plan.py (board state, kept up to date),
# shots.json (current pages, durations, order), the round-12 board data (beat
# action text) and the film folders (pictures, clips); writes
# zula_end_frame_board.html plus t/, full/ and video/ next to it.
# Run:  python build_local.py
import json, os, io, base64, shutil, sys
from collections import Counter
from PIL import Image

BOARD = os.path.dirname(os.path.abspath(__file__))
FILM = os.path.abspath(os.path.join(BOARD, '..', '..', '..'))
os.chdir(BOARD)

# ---------- 1) board state from plan.py ----------
P = {}
def r(st, start, sn, end, ed, ref=None, sref=None, note=''):
    P[st] = dict(start=start, startNote=sn, end=end, endDesc=ed, endRef=ref, startRef=sref, note=note)
OK, MID, ENDS = 'ok', 'mid', 'ends'
def u(st, **kw): P[st].update(kw)
exec(open('plan.py', encoding='utf-8').read())

# ---------- 2) pages from shots.json (current order + durations) ----------
SH = json.load(open(os.path.join(FILM, 'shots.json'), encoding='utf-8'))
SEQ = {s['seq']: s for s in SH['sequences']}
CUT = set()  # shots.json already excludes cut pages
pages = []
for s in sorted(SH['shots'], key=lambda x: (x['editorial_start_s'], x['id'])):
    sid = s['id']
    # a page's own name (e.g. the coda borrows 058's still file); match by shot id first
    st = next((k for k in P if '_' + sid + '_' in k + '_'), None) or \
         os.path.basename(s['still'] or '').rsplit('.', 1)[0]
    if st not in P or st in CUT:
        continue
    pages.append((st, sid, float(s['duration']), st))

# ---------- 3) beat text from the round-12 board ----------
R12 = {}
if os.path.exists('r12_data.json'):
    R12 = {row['id']: row for row in json.load(open('r12_data.json', encoding='utf-8'))['rows']}

def beat(st, sid):
    shot = next(x for x in SH['shots'] if x['id'] == sid)
    seq = SEQ[shot['seq']]
    old = R12.get(st, {})
    return dict(
        id=st, title=shot['title'], seq='%02d' % shot['seq'],
        seqname=seq['title'], seqtime=seq['header'].split('|')[0].strip(),
        action=old.get('action') or (shot.get('prompt') or '')[:220],
        applied=bool(old.get('applied')))

bmap = {b['id']: b for b in (beat(*p[:2]) for p in pages)}

# ---------- 4) picture sources: index the film by file basename ----------
SKIP_DIRS = {'source', 'references', '__pycache__', 't', 'full', 'video'}
INDEX = {}          # basename-no-ext -> best path (earlier roots win)
def index_root(rel):
    root = os.path.join(FILM, rel)
    if not os.path.isdir(root): return
    for dp, dns, fns in os.walk(root):
        dns[:] = [d for d in dns if d not in SKIP_DIRS]
        for fn in fns:
            k, ext = os.path.splitext(fn)
            if ext.lower() in ('.png', '.jpg', '.jpeg', '.mp4') and k not in INDEX:
                INDEX[k] = os.path.join(dp, fn)
for rel in ('stills', 'proxies', 'assets', 'sets', 'scenes',
            r'review\handoff_20nov\pending', r'review\round13', r'review\round11',
            r'review\round12', 'alternates'):
    index_root(rel)
index_root(r'..\Claude outputs')

R12SRC = {}
rsrc = os.path.join(FILM, r'review\round12\triage\sources.json')
if os.path.exists(rsrc):
    R12SRC = json.load(open(rsrc, encoding='utf-8'))

PREFIXES = ['asset_', 'r13_', 'r13d_', 'r13e_', 'r13f_', 'r13g_', 'ef_', 'ef2_', 'ef3_',
            'se_', 'sb_', 'ad_', 'age_', 'ag_', 'a3_', 'a4_', 'prop_', 'pose_', 'light_',
            'df_', 'fl_', 'g4_', 'g5_', 'geese_', 's07_', 'mv_', 'mv2_', 'mv3_', 'r11_',
            'fo_', 'rd_', 's42_', 's34_', 's1005_', 'lora_']
def find_pic(k):
    for cand in [k] + [k[len(p):] for p in PREFIXES if k.startswith(p)]:
        for base, exts in ((cand, ('.png', '.jpg', '.jpeg')),):
            for ext in exts:
                for folder in ('proxies', 'stills', 'assets'):
                    p = os.path.join(FILM, folder, base + ext)
                    if os.path.exists(p): return p
        if cand in INDEX and INDEX[cand].lower().endswith(('.png', '.jpg', '.jpeg')):
            return INDEX[cand]
    hint = R12SRC.get(k)
    if hint:
        p = os.path.join(FILM, hint)
        if os.path.exists(p): return p
    return PIC_MAP.get(k)

# sandbox pictures that were later approved and filed: where each one now lives.
# A missing start/end ref on a page falls back to that page's filed asset frame.
PIC_MAP = {
    'pose_021b_end': os.path.join(FILM, r'review\handoff_20nov\pending\S06_01_b_end_new.png'),
    '076_S13_03_Coda_asleep_in_the_moonlight': os.path.join(FILM, r'stills\058_S10_05_Asleep_in_the_moonlight.png'),
}

# ---------- 5) thumbs + full-size ----------
os.makedirs(r't\thumbs', exist_ok=True)
os.makedirs('full', exist_ok=True)
TH, SRC, FULL, MISSING = {}, {}, [], []
STILL_REPAINT = ('prop_', 'pose_', 'age_', 'ag_', 'light_', 'df_', 'fl_', 'g4_', 'g5_',
                 'r13_', 'r13d_', 'r13e_', 'r13f_', 'r13g_', 'lora_', 'a3_', 'a4_', 'r11_')
def thumb(k, shot=None, side=None, still_id=None):
    if k is None or k in TH: return
    src = find_pic(k)
    if not src and still_id and k.startswith(STILL_REPAINT):
        # a repainted version of the still: the repaint was filed as the still
        p = os.path.join(FILM, 'stills', still_id + '.png')
        if os.path.exists(p): src = p
    if not src and shot and side:      # lost sandbox ref -> the page's filed asset frame
        p = os.path.join(FILM, 'assets', f'{shot}_{side}.png')
        if os.path.exists(p): src = p
    if not src:                        # then the page still itself
        p = os.path.join(FILM, 'stills', k + '.png')
        if os.path.exists(p): src = p
    if not src:
        MISSING.append(k); return
    im = Image.open(src).convert('RGB')
    small = im.resize((320, 180), Image.LANCZOS)
    b = io.BytesIO(); small.save(b, 'JPEG', quality=72)
    TH[k] = 'data:image/jpeg;base64,' + base64.b64encode(b.getvalue()).decode()
    if im.width > 1920:
        im = im.resize((1920, round(im.height * 1920 / im.width)), Image.LANCZOS)
    fj = os.path.join('full', k + '.jpg')
    im.save(fj, 'JPEG', quality=88)
    FULL.append(k); SRC[k] = os.path.relpath(src, FILM)

# ---------- 6) videos ----------
os.makedirs('video', exist_ok=True)
VIDEO_MAP = {
    't_021b_v3.mp4': r'review\handoff_20nov\pending\021b_S06_01_b_Geese_v3.mp4',
    't_025_v3.mp4':  r'review\handoff_20nov\pending\025_S06_04_b_Empty_games_v3.mp4',
    't_023_v4.mp4':  r'clips\023_S06_03_The_stream_without_her.mp4',
    't_026_v4.mp4':  r'clips\026_S06_05_Returning_alone.mp4',
    't_018c1.mp4':  r'review\handoff_20nov\pending\018_clip1_S05_06_Peek_v1.mp4',
    't_018c2.mp4':  r'review\handoff_20nov\pending\018_clip2_S05_06_Paws_over_his_eyes_v1.mp4',
}
LOST = ' [video lost with the old claude.ai session — ask for a re-render]'
def resolve_video(name, row_id, approved):
    if approved:
        p = os.path.join(FILM, 'clips', row_id + '.mp4')
        if os.path.exists(p): return p
    if name in VIDEO_MAP:
        p = os.path.join(FILM, VIDEO_MAP[name])
        if os.path.exists(p): return p
    k = os.path.splitext(name)[0]
    if k in INDEX and INDEX[k].lower().endswith('.mp4'): return INDEX[k]
    alt = os.path.join(FILM, 'clips', row_id + '.mp4')
    return alt if os.path.exists(alt) else None

# ---------- 7) rows ----------
rows = []
for st, sid, dur, bid in pages:
    b, p = bmap[bid], P[st]
    thumb(st)
    thumb(p.get('endRef'), sid, 'end', st)
    thumb(p.get('startRef'), sid, 'start', st)
    d = float(dur)
    clip = 0 if p['end'] == 'NONE' else max(5, round(d + 0.49))
    paint = (1 if p['end'] in ('NUDGE', 'NEW') else 0) + \
            (1 if p['start'] == 'ends' and not p.get('startRef') else 0)
    row = dict(id=st, shot=sid, dur=d, clip=clip, paint=paint, **{k: b[k] for k in
            ('title', 'seq', 'seqname', 'seqtime', 'action', 'applied')}, **p)
    approved = p.get('r13') == 'approved'
    if row.get('video'):
        src = resolve_video(os.path.basename(row['video']), st, approved)
        if src: shutil.copy2(src, os.path.join('video', os.path.basename(row['video'])))
        else:
            row.pop('video'); row['r13note'] = (row.get('r13note') or '') + LOST
    if row.get('videos'):
        kept = []
        for label, pathv in row['videos']:
            src = resolve_video(os.path.basename(pathv), st, False)
            if src:
                shutil.copy2(src, os.path.join('video', os.path.basename(pathv)))
                kept.append([label, pathv])
        row['videos'] = kept
    rows.append(row)

json.dump(dict(src=SRC), open('sources_local.json', 'w', encoding='utf-8'))

# ---------- 8) template patches + output ----------
tpl = open('board_tpl.html', encoding='utf-8').read()
assert '/*DATA*/null' in tpl
data = json.dumps(dict(rows=rows, thumbs=TH, full=FULL, src=SRC))
out = tpl.replace('/*DATA*/null', data)
# board decisions persist in this browser (the claude.ai db is not reachable here)
out = out.replace(
    "let decisions = {}, filter = 'all', db = null, canWrite = false;",
    "let decisions = {}, filter = 'all', db = null, canWrite = false;\n"
    "try{ decisions = JSON.parse(localStorage.getItem('zula_decisions')||'{}'); }catch(e){}")
out = out.replace(
    'if (!db) return;',
    "if (!db) { decisions[id]=cur; try{ const all=JSON.parse(localStorage.getItem('zula_decisions')||'{}');"
    " all[id]=cur; localStorage.setItem('zula_decisions', JSON.stringify(all)); }catch(e){}"
    " const el2=document.getElementById('s-'+id); if (el2) el2.textContent='Saved locally ' +"
    " new Date().toLocaleTimeString([], {hour:'numeric', minute:'2-digit'}); return; }")
# a lost reference picture falls back to the page still instead of a broken image
out = out.replace('src="${T[k]}">', 'src="${T[k]||T[r.id]||\'\'}">')
out = out.replace('Built from the rev 2.9 shot cards',
                  'LOCAL REBUILD (20 Nov 2026, this computer) · Built from the rev 2.9 shot cards')
open('zula_end_frame_board.html', 'w', encoding='utf-8').write(out)

print('pages:', len(rows))
print('ends:', Counter(r_['end'] for r_ in rows), 'starts:', Counter(r_['start'] for r_ in rows))
print('paint:', sum(r_['paint'] for r_ in rows), 'clip s:', sum(r_['clip'] for r_ in rows))
print('thumbs:', len(TH), 'full:', len(FULL), 'missing refs:', len(MISSING))
for k in sorted(set(MISSING)): print('  missing:', k)
