import cv2
import time
from ultralytics import YOLO
from seguimiento2 import GlobalMemory, CamManager, dibujar_track

def test_video(video_path):
    print(f"Iniciando Benchmark de Video: {video_path}")
    model = YOLO("yolov8n.pt")
    global_mem = GlobalMemory()
    manager = CamManager("TEST_CAM", global_mem)
    
    cap = cv2.VideoCapture(video_path)
    cv2.namedWindow("Benchmark TT", cv2.WINDOW_AUTOSIZE)
    
    while cap.isOpened():
        ret, frame = cap.read()
        if not ret: break
        
        now = time.time()
        frame_show = cv2.resize(frame, (480, 270))
        
        # Inferencia frame por frame sin hilos (sincrónico)
        res = model.predict(frame_show, conf=0.40, iou=0.50, classes=[0], verbose=False, imgsz=480, device='cpu')
        boxes = res[0].boxes.xyxy.cpu().numpy().tolist() if res[0].boxes else []
        
        tracks = manager.update(boxes, frame_show, now, turno_activo=True)
        
        for trk in tracks:
            if trk.time_since_update == 0:
                dibujar_track(frame_show, trk)
                
        cv2.imshow("Benchmark TT", frame_show)
        
        # Si presionas espacio se pausa, con 'q' sales
        key = cv2.waitKey(30) & 0xFF
        if key == ord('q'): break
        elif key == ord(' '): cv2.waitKey(-1)
            
    cap.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    test_video("video.mp4") # Pon aquí el nombre de tu video