"""Make an approximately aligned scene/pose replay from recorded receipt times."""
import bisect, csv, json, subprocess, sys
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw, ImageFont
from sync_capture import FFMPEG, nearest_pose_index


def past_index(values, target):
    i=bisect.bisect_right(values,target)-1
    return i if i>=0 else None


def read_rows(path):
    with path.open(encoding='utf-8',newline='') as f: return list(csv.DictReader(f))


def make(session):
    session=Path(session); video=read_rows(session/'video_frames.csv'); poses=read_rows(session/'pose'/'pose.csv')
    vt=[int(r['host_monotonic_ns']) for r in video]; pt=[int(r['host_monotonic_ns']) for r in poses]
    if not vt or not pt or any(a>b for a,b in zip(vt,vt[1:])) or any(a>b for a,b in zip(pt,pt[1:])): raise ValueError('Invalid or unordered receipt timestamps')
    start=max(vt[0],pt[0]); end=min(vt[-1],pt[-1]); fps=15
    if end<=start: raise ValueError('Video and pose do not overlap')
    out=session/'comparison.mp4'
    if out.exists(): raise FileExistsError(str(out))
    xyz=np.array([[float(r[k]) for k in ('x','y','z')] for r in poses]); rel=xyz-xyz[0]
    # Oblique projection only for displaying a 3D trace; axes are not registered to video.
    uv=np.column_stack((rel[:,0]-.5*rel[:,1], -rel[:,2]-.35*rel[:,1])); center=(uv.max(axis=0)+uv.min(axis=0))/2; extent=max(float(np.ptp(uv,axis=0).max()),.01)
    xy=(uv-center)*(300/extent)+np.array([960,278]); xy=np.clip(xy,[-10000,-10000],[10000,10000])
    font_path='C:/Windows/Fonts/msyh.ttc'; font=ImageFont.truetype(font_path,22); small=ImageFont.truetype(font_path,17); title=ImageFont.truetype(font_path,26)
    dec=subprocess.Popen([FFMPEG,'-loglevel','error','-i',str(session/'scene.mp4'),'-vf','scale=640:480','-f','rawvideo','-pix_fmt','rgb24','pipe:1'],stdout=subprocess.PIPE)
    enc=subprocess.Popen([FFMPEG,'-loglevel','error','-f','rawvideo','-pixel_format','rgb24','-video_size','1280x720','-framerate',str(fps),'-i','pipe:0','-an','-c:v','libx264','-pix_fmt','yuv420p','-movflags','+faststart',str(out)],stdin=subprocess.PIPE)
    size=640*480*3; current=-1; frame=None; missing=0; repeats=0; last_video=-1; emitted=0
    try:
        for k in range(int((end-start)*fps//1_000_000_000)+1):
            clock=start+k*1_000_000_000//fps; vi=past_index(vt,clock); pi=nearest_pose_index(pt,clock,100_000_000)
            while current<vi:
                block=dec.stdout.read(size)
                if len(block)!=size: raise RuntimeError('Decoded video shorter than timestamp index')
                current+=1; frame=Image.frombytes('RGB',(640,480),block)
            repeats+=int(vi==last_video); last_video=vi
            canvas=Image.new('RGB',(1280,720),'white'); canvas.paste(frame,(0,94)); draw=ImageDraw.Draw(canvas)
            draw.rectangle((0,0,1279,70),fill=(25,39,59)); draw.text((24,18),'T265 实景与估计轨迹：按主机接收时间近似对齐',font=title,fill='white')
            draw.text((20,70),'电脑摄像头实景（无声）',font=small,fill='#28384d'); draw.text((670,78),'三维轨迹投影（T265 估计值）',font=font,fill='#28384d')
            draw.rectangle((660,112,1260,445),outline='#bac7d4',width=2)
            if pi is None:
                missing+=1; draw.text((680,260),'此时间点没有可匹配的位姿',font=font,fill='#ae3e22')
            else:
                inds=np.arange(0,pi+1,max(1,(pi+1)//1000)); inds=np.unique(np.r_[inds,pi]); points=[tuple(xy[i]) for i in inds]
                if len(points)>1: draw.line(points,fill='#1476ad',width=3)
                x,y=xy[pi]; draw.ellipse((x-6,y-6,x+6,y+6),fill='#d55524'); draw.ellipse((xy[0,0]-5,xy[0,1]-5,xy[0,0]+5,xy[0,1]+5),fill='#009e73')
                diff=(pt[pi]-vt[vi])/1e6
                draw.text((676,465),'当前位置（米，SDK 坐标）',font=font,fill='#28384d')
                for j,name in enumerate('XYZ'): draw.text((680,500+31*j),f'{name}: {xyz[pi,j]:+.4f}',font=font,fill='#134f75')
                draw.text((680,608),f'视频帧 / 位姿接收时差：{diff:+.0f} ms',font=small,fill='#28384d')
            draw.text((20,596),f'记录相对时间：{(clock-start)/1e9:05.2f} 秒',font=font,fill='#28384d')
            draw.text((20,635),'帧间隔按接收时间重排；低帧率处重复上一画面',font=small,fill='#4e5e70')
            draw.text((20,666),'接收时间仅近似对齐，非硬件同步；轨迹不是实际位置真值',font=small,fill='#734923')
            enc.stdin.write(canvas.tobytes()); emitted+=1
    finally:
        if dec.poll() is None: dec.terminate()
        dec.wait(); enc.stdin.close(); result=enc.wait()
    if result: raise RuntimeError('video encoder failed')
    meta={'source_video':'scene.mp4','pose':'pose/pose.csv','duration_s':(end-start)/1e9,'output_fps':fps,'output_frames':emitted,'repeated_scene_frames':repeats,'unmatched_pose_frames':missing,'scene_frames':len(video),'note':'Frames are held until the next recorded frame according to host receipt timestamps; no interpolation. Approximate receipt-time alignment is not hardware synchronization; camera pose in video has not been calibrated to T265 coordinates.'}
    (session/'comparison_metadata.json').write_text(json.dumps(meta,ensure_ascii=False,indent=2),encoding='utf-8'); print(json.dumps(meta,indent=2))

if __name__=='__main__': make(sys.argv[1])
