"""ArUco camera observation: reports pixel separation, not physical opening."""
import argparse, csv, time
from pathlib import Path
import cv2

def main():
 p=argparse.ArgumentParser(); p.add_argument('--output',required=True); p.add_argument('--camera',type=int,default=0); p.add_argument('--duration',type=float,default=30); args=p.parse_args()
 if args.duration<=0: raise ValueError('duration must be positive')
 out=Path(args.output); out.mkdir(parents=True,exist_ok=False)
 camera=cv2.VideoCapture(args.camera,cv2.CAP_DSHOW)
 if not camera.isOpened(): raise RuntimeError('Cannot open webcam')
 detector=cv2.aruco.ArucoDetector(cv2.aruco.getPredefinedDictionary(cv2.aruco.DICT_4X4_50),cv2.aruco.DetectorParameters())
 start=time.monotonic(); count=0; both=0
 try:
  with (out/'observations.csv').open('x',newline='',encoding='utf-8') as f:
   w=csv.writer(f);w.writerow(['frame','host_monotonic_ns','id0_visible','id1_visible','id0_x_px','id0_y_px','id1_x_px','id1_y_px','center_distance_px'])
   while time.monotonic()-start<args.duration:
    ok,frame=camera.read()
    if not ok: raise RuntimeError('camera frame unavailable')
    t=time.monotonic_ns(); corners,ids,_=detector.detectMarkers(frame); centers={}
    if ids is not None:
     cv2.aruco.drawDetectedMarkers(frame,corners,ids)
     centers={int(i):c.reshape(4,2).mean(axis=0) for i,c in zip(ids.ravel(),corners)}
    x0,y0=centers.get(0,('',''));x1,y1=centers.get(1,('',''));dist=''
    if 0 in centers and 1 in centers:
     dist=float(((centers[0]-centers[1])**2).sum()**.5); both+=1
    w.writerow([count,t,int(0 in centers),int(1 in centers),x0,y0,x1,y1,dist]); f.flush()
    cv2.putText(frame,'IDs 0/1; pixel distance: '+(f'{dist:.1f}' if dist!='' else 'unavailable'),(12,30),cv2.FONT_HERSHEY_SIMPLEX,.65,(0,0,255),2)
    cv2.imshow('ArUco measurement (pixels; q stops)',frame)
    if count==0: cv2.imwrite(str(out/'first_frame.png'),frame)
    count+=1
    if cv2.waitKey(1)&0xff==ord('q'): break
 finally: camera.release();cv2.destroyAllWindows()
 print('frames:',count,'frames with both IDs:',both,'output:',out)
if __name__=='__main__': main()
