#!/usr/bin/env python3
"""Short, synchronised repair comparisons and reproducible application requests."""
import argparse
import copy
import html
import json
from pathlib import Path
import shlex
import subprocess
from fractions import Fraction
from repair_plan import build_plan,bound_file,digest
from repair_preview import render


def build(request_path,out_dir,context=2):
    request_path=Path(request_path).resolve();root=request_path.parent
    request=json.loads(request_path.read_text());plan=build_plan(request,root)
    if len(request['defects'])!=1:raise ValueError('Review one defect at a time')
    if not 0<=context<=10:raise ValueError('Context must be between zero and ten seconds')
    out_dir=Path(out_dir).resolve();out_dir.mkdir(parents=True,exist_ok=False)
    # Saved requests remain usable from their new directory.
    for record in [request['master'],request['selection'],*[r['source'] for r in request['ranges']],*request.get('clipBindings',{}).values()]:
        record['path']=str(bound_file(record,root))
    fps=Fraction(plan['fps']);defect=request['defects'][0]
    start=max(0,defect['startFrame']-round(context*fps));end=min(plan['totalFrames'],defect['endFrame']+round(context*fps))
    original=out_dir/'original.mp4'
    subprocess.run(['ffmpeg','-v','error','-nostdin','-i',request['master']['path'],'-ss',str(float(start/fps)),'-t',str(float((end-start)/fps)),'-vf','setpts=PTS-STARTPTS','-c:v','libx264','-preset','fast','-c:a','aac',str(original)],check=True)
    cards=[];results=[]
    for index,item in enumerate(request['ranges']):
        full=copy.deepcopy(request);full['ranges']=[item]
        candidate=build_plan(full,root)
        reasons=[o.get('reason') for o in candidate['options'] if o.get('reason')]
        if not candidate['edits']:
            cards.append(f'<section><h2>{html.escape(item["id"])}</h2><p>Not eligible: {html.escape("; ".join(reasons))}</p></section>');continue
        folder=out_dir/f'option-{index}';folder.mkdir()
        chosen=folder/'apply-request.json';chosen.write_text(json.dumps(full,indent=2))
        sample=copy.deepcopy(full);sample.update(totalFrames=end-start,master={'path':str(original),'sha256':digest(original)})
        sample['defects'][0]['startFrame']-=start;sample['defects'][0]['endFrame']-=start
        # Prior-use checks were performed on the complete original timeline above.
        for r in sample['ranges']:r['priorUses']=[]
        req=folder/'sample-request.json';req.write_text(json.dumps(sample,indent=2))
        report=render(req,folder/'preview');data=json.loads(report.read_text())
        command=shlex.join(['python3',str(Path(__file__).with_name('repair_apply.py')),'--request',str(chosen),'--out-dir',str(folder/'applied')])
        relative=Path(data['output']).relative_to(out_dir).as_posix()
        cards.append(f'<section><h2>{html.escape(item["id"])}</h2><p>Source frames {item["inFrame"]}–{item["outFrame"]}; destination {defect["startFrame"]}–{defect["endFrame"]}. Audio unchanged within this comparison.</p><video controls preload="metadata" src="{html.escape(relative,quote=True)}"></video><p>{html.escape("; ".join(item.get("cautions",[])))}</p><details><summary>Apply this option to a new selection</summary><p>Run this command after reviewing motion and the return to the performer:</p><pre>{html.escape(command)}</pre></details></section>')
        results.append(dict(rangeId=item['id'],request=str(chosen),preview=data['output'],gaps=candidate['gaps'],applyCommand=command))
    page='''<!doctype html><meta charset="utf-8"><title>Repair comparisons</title><style>body{background:#11161d;color:#eee;font:17px system-ui;margin:32px}main{display:grid;grid-template-columns:repeat(auto-fit,minmax(400px,1fr));gap:24px}video{width:100%}section{background:#1c2530;padding:20px;border-radius:12px}pre{white-space:pre-wrap;overflow-wrap:anywhere}button{padding:12px}</style><h1>Repair comparisons</h1><p>One defect, existing footage. Original sound is shared across the comparison interval. Inspect mouths, motion and both joins; geometry is not artistic approval.</p><button id="play">Play together</button> <button id="pause">Pause all</button><main><section><h2>Original</h2><video controls preload="metadata" src="original.mp4"></video></section>'''+''.join(cards)+'''</main><script>const videos=[...document.querySelectorAll('video')];document.querySelector('#play').onclick=()=>{const t=videos[0].currentTime;videos.forEach((v,i)=>{v.currentTime=t;v.muted=i>0;v.play().catch(()=>{});});};document.querySelector('#pause').onclick=()=>videos.forEach(v=>v.pause());</script>'''
    (out_dir/'index.html').write_text(page)
    (out_dir/'options.json').write_text(json.dumps(results,indent=2))
    return out_dir/'index.html'


if __name__=='__main__':
    ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('--request',type=Path,required=True);ap.add_argument('--out-dir',type=Path,required=True);ap.add_argument('--context',type=float,default=2);a=ap.parse_args()
    try:print(build(a.request,a.out_dir,a.context))
    except (ValueError,KeyError,OSError,subprocess.SubprocessError) as e:ap.error(str(e))
