"""Simple test to build a video from images in dumps/ using DumpManager."""
import os
import sys
import logging
from time import sleep

# Ensure package root is on sys.path so we can import local package
sys.path.insert(0, os.getcwd())
from VideoReceiverSFP.core.dump_manager import DumpManager
try:
    from PIL import Image
except Exception:
    Image = None

logging.basicConfig(level=logging.INFO, format='[%(levelname)s] %(message)s')

dumps_dir = os.path.join(os.getcwd(), 'dumps')
if not os.path.isdir(dumps_dir):
    print('No dumps directory found at', dumps_dir)
    raise SystemExit(1)

# collect image files
img_files = [os.path.join(dumps_dir, f) for f in sorted(os.listdir(dumps_dir)) if f.lower().endswith(('.png','.jpg','.jpeg','.bmp'))]
if not img_files:
    print('No image files found in dumps to build test video')
    raise SystemExit(1)

# open first image to get size
first = img_files[0]
if Image is None:
    print('Pillow not available')
    raise SystemExit(1)

img = Image.open(first).convert('RGB')
w, h = img.size
print('Using frame size', w, 'x', h, 'fps=20')

mgr = DumpManager(dumps_dir, keep_count=100)
started = mgr.start_video_record('mfd', w, h, fps=20)
if not started:
    print('Failed to start video writer (OpenCV available?)')
    raise SystemExit(1)

# write up to N frames
N = min(40, len(img_files))
for i, p in enumerate(img_files[:N]):
    try:
        frame = Image.open(p).convert('RGB')
        mgr.write_video_frame(frame, 'mfd')
        print(f'Wrote frame {i+1}/{N}: {p}')
    except Exception as e:
        print('Failed writing frame', p, e)

# allow writer to flush
sleep(0.5)
mgr.stop_video_record('mfd')
print('Video recording test completed; check dumps/ for output .avi')
