# -*- coding: utf-8 -*-
"""从 ep-NN-results.json + ep-NN-specs.json 构建 ep-NN.json（切法重映射到 spec.plan，修正代理乱改秒数）。"""
import json, os
base = '小说2/storyboard-work'
for ep in range(1, 46):
    tag = '%02d' % ep
    resf = os.path.join(base, 'ep%s-results.json' % tag)
    spf = os.path.join(base, 'ep-%s-specs.json' % tag)
    seedf = os.path.join(base, 'ep-%s-seed.json' % tag)
    if not os.path.exists(resf) or not os.path.exists(spf):
        continue
    res = [s for s in json.load(open(resf, encoding='utf-8')) if s and s.get('id')]
    if not res: continue
    specs = {s['seg']: s for s in json.load(open(spf, encoding='utf-8'))['specs']}
    seed = json.load(open(seedf, encoding='utf-8'))
    out_segs = []
    for s in res:
        spec = specs.get(s['id'])
        if not spec:
            out_segs.append(s); continue
        cuts = []
        for i, p in enumerate(spec['plan']):
            ag = s.get('cuts') or []
            a = ag[i] if i < len(ag) else {}
            cuts.append({
                'beats': [p[0], p[1]],
                'seconds': p[2],
                'size': str(a.get('size') or 'medium'),
                'camera': str(a.get('camera') or 'Static Shot'),
                'characters': a.get('characters') if isinstance(a.get('characters'), list) else [],
                'props': a.get('props') if isinstance(a.get('props'), list) else [],
                'frame': str(a.get('frame') or '')
            })
        out_segs.append({'id': s['id'], 'sceneIndex': s.get('sceneIndex'), 'cuts': cuts, 'sound': s.get('sound') or '', 'music': s.get('music') or 'N/A'})
    out_segs.sort(key=lambda x: x['id'])
    json.dump({'ep': ep, 'segments': out_segs, 'seedScenes': seed.get('seedScenes', [])}, open(os.path.join(base, 'ep-%s.json' % tag), 'w', encoding='utf-8'), ensure_ascii=False, indent=1)
    print('built ep-%s.json segs=%d' % (tag, len(out_segs)))
