"""Record webcam frames with receipt timestamps alongside T265 pose.
Clock association is approximate, not exposure-time or hardware synchronization.
"""
import argparse, bisect, csv, json, subprocess, threading, time
from pathlib import Path
from capture import RealSenseSource, record_session

FFMPEG = 'ffmpeg'
WIDTH, HEIGHT, FPS = 320, 240, 30


def nearest_pose_index(times, target, max_delta_ns):
    if not times: return None
    i=bisect.bisect_left(times,target)
    candidates=[j for j in (i-1,i) if 0<=j<len(times)]
    best=min(candidates,key=lambda j:abs(times[j]-target))
    return best if abs(times[best]-target)<=max_delta_ns else None


def write_associations(video_csv, pose_csv, output_csv, max_delta_ns=100_000_000):
    with Path(video_csv).open(encoding='utf-8',newline='') as f: video=list(csv.DictReader(f))
    with Path(pose_csv).open(encoding='utf-8',newline='') as f: poses=list(csv.DictReader(f))
    times=[int(r['host_monotonic_ns']) for r in poses]
    if any(a>b for a,b in zip(times,times[1:])): raise ValueError('pose receipt timestamps not ordered')
    count=0
    with Path(output_csv).open('x',encoding='utf-8',newline='') as f:
        keys=['video_frame_index','video_host_monotonic_ns','pose_frame_number','pose_host_monotonic_ns','receipt_time_difference_ms','x','y','z']
        w=csv.DictWriter(f,fieldnames=keys); w.writeheader()
        for frame in video:
            now=int(frame['host_monotonic_ns']); i=nearest_pose_index(times,now,max_delta_ns)
            row={'video_frame_index':frame['frame_index'],'video_host_monotonic_ns':now}
            if i is not None:
                p=poses[i]; row.update({'pose_frame_number':p['frame_number'],'pose_host_monotonic_ns':times[i], 'receipt_time_difference_ms':(times[i]-now)/1e6,'x':p['x'],'y':p['y'],'z':p['z']}); count+=1
            w.writerow(row)
    return count


class WebcamRecorder:
    def __init__(self, output, device='FHD Webcam', synthetic=False):
        self.output=Path(output); self.device=device; self.synthetic=synthetic
        self.ready=threading.Event(); self.stop_event=threading.Event(); self.error=None; self.count=0; self.decoder=None
    def start(self):
        self.thread=threading.Thread(target=self._run,daemon=True); self.thread.start()
        if not self.ready.wait(20):
            self.stop(); raise RuntimeError('No camera frame received within 20 seconds')
        if self.error:
            self.stop(); raise RuntimeError('Camera failed: '+str(self.error))
    def _run(self):
        enc=None
        try:
            if self.synthetic:
                inp=['-re','-f','lavfi','-i','testsrc2=size=640x480:rate=30']
            else:
                inp=['-f','dshow','-video_size','640x480','-framerate','30','-i','video='+self.device]
            dec_cmd=[FFMPEG,'-loglevel','error',*inp,'-an','-vf','scale=320:240','-pix_fmt','rgb24','-fps_mode','passthrough','-f','rawvideo','pipe:1']
            enc_cmd=[FFMPEG,'-loglevel','error','-f','rawvideo','-pixel_format','rgb24','-video_size','320x240','-framerate','30','-i','pipe:0','-an','-c:v','libx264','-pix_fmt','yuv420p','-movflags','+faststart',str(self.output/'scene.mp4')]
            self.decoder=subprocess.Popen(dec_cmd,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,bufsize=0)
            enc=subprocess.Popen(enc_cmd,stdin=subprocess.PIPE,stderr=subprocess.DEVNULL,bufsize=0)
            with (self.output/'video_frames.csv').open('x',newline='',encoding='utf-8') as f:
                w=csv.writer(f); w.writerow(['frame_index','video_nominal_time_s','host_unix_ns','host_monotonic_ns']); f.flush()
                size=WIDTH*HEIGHT*3
                while not self.stop_event.is_set():
                    frame=bytearray()
                    while len(frame)<size:
                        chunk=self.decoder.stdout.read(size-len(frame))
                        if not chunk: break
                        frame.extend(chunk)
                    if len(frame)!=size:
                        if not self.stop_event.is_set(): raise RuntimeError('Camera stream ended or frame was incomplete')
                        break
                    mono=time.monotonic_ns(); wall=time.time_ns()
                    enc.stdin.write(frame)
                    w.writerow([self.count,self.count/FPS,wall,mono]); f.flush(); self.count+=1; self.ready.set()
        except Exception as e:
            self.error=e; self.ready.set()
        finally:
            if self.decoder and self.decoder.poll() is None: self.decoder.terminate()
            if enc:
                try:
                    enc.stdin.close(); code=enc.wait(timeout=20)
                    if code!=0 and self.error is None: self.error=RuntimeError('Video encoder failed with exit code '+str(code))
                except Exception as e:
                    enc.kill(); enc.wait(); self.error=self.error or e
    def stop(self):
        self.stop_event.set()
        if self.decoder and self.decoder.poll() is None: self.decoder.terminate()
        if hasattr(self,'thread'):
            self.thread.join(timeout=25)
            if self.thread.is_alive(): raise RuntimeError('Camera thread did not stop')
        if self.error: raise RuntimeError('Camera recording failed: '+str(self.error))


def run(directory, duration=30, device='FHD Webcam'):
    if duration<=0: raise ValueError('duration must be positive')
    directory=Path(directory); directory.mkdir(parents=True,exist_ok=False)
    camera=WebcamRecorder(directory,device); state={'status':'starting','duration_s':duration,'camera':device,'sync':'Approximate association by host monotonic frame receipt timestamps. Not exposure time or hardware synchronization. Video MP4 uses nominal 30 fps; frame-to-time mapping is video_frames.csv.'}
    try:
        camera.start(); print('摄像头已开始录制，正在启动 T265；看到提示后开始动作。',flush=True)
        record_session(RealSenseSource(),directory/'pose',duration,display=True)
        state['status']='completed'
    except BaseException as e:
        state['status']='error'; state['error']=f'{type(e).__name__}: {e}'; raise
    finally:
        try: camera.stop()
        except Exception as e:
            state['status']='error'; state['camera_error']=str(e)
        state['camera_frames']=camera.count
        (directory/'sync_metadata.json').write_text(json.dumps(state,ensure_ascii=False,indent=2),encoding='utf-8')
    if state['status']!='completed': raise RuntimeError(state.get('camera_error','recording failed'))
    try:
        state['associated_frames']=write_associations(directory/'video_frames.csv',directory/'pose'/'pose.csv',directory/'frame_pose_association.csv')
    except Exception as e:
        state['status']='error'; state['association_error']=str(e); raise
    finally:
        (directory/'sync_metadata.json').write_text(json.dumps(state,ensure_ascii=False,indent=2),encoding='utf-8')

if __name__=='__main__':
    parser=argparse.ArgumentParser(); parser.add_argument('--session',required=True); parser.add_argument('--duration',type=float,default=30); parser.add_argument('--device',default='FHD Webcam')
    args=parser.parse_args(); run(args.session,args.duration,args.device)
