#!/usr/bin/env python3
"""Подставляет в монтажный план секунды из word_id, исключая ручной независимый таймер."""
from __future__ import annotations
import argparse, hashlib, json
from pathlib import Path

def sha(p): return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def main():
    ap=argparse.ArgumentParser(); ap.add_argument('edit_plan'); ap.add_argument('timeline'); ap.add_argument('--out',default='edit_plan.resolved.json'); args=ap.parse_args()
    plan=json.loads(Path(args.edit_plan).read_text(encoding='utf-8')); t=json.loads(Path(args.timeline).read_text(encoding='utf-8'))
    words={w['id']:w for w in t['words']}
    for s in plan['scenes']:
        a=int(s['anchor_word_start']); b=int(s['anchor_word_end'])
        if a not in words or b not in words or b<a: raise SystemExit(f"Неверные якоря сцены {s.get('id')}")
        s['resolved_start']=words[a]['start']; s['resolved_end']=words[b]['end']
        s['spoken_text']=' '.join(words[i]['word'] for i in range(a,b+1) if i in words)
    plan['timeline']={'path':args.timeline,'sha256':sha(args.timeline),'expected_duration':t['expected_duration']}
    Path(args.out).write_text(json.dumps(plan,ensure_ascii=False,indent=2),encoding='utf-8')
    print(json.dumps({'out':args.out,'scenes':len(plan['scenes'])},ensure_ascii=False))
if __name__=='__main__': main()
