import logging, time, cv2
from camera import create_camera

logging.basicConfig(level=logging.INFO)


def main():
    cam = create_camera(width=640, height=480, fps=30, mock=False)
    if not cam.open():
        print("❌ Impossible d'ouvrir la caméra (Picamera2 requis).")
        return

    print(f"✅ Caméra ouverte (backend={getattr(cam, '_backend', 'inconnu')})")

    got, last = 0, None
    for _ in range(100):
        frame = cam.read_frame()
        if frame is None:
            print("⚠️  Frame non valide")
            time.sleep(0.01)
            continue
        got += 1
        last = frame

    avg_fps, nframes = cam.get_fps_stats()
    print(f"📊 Capturé {got}/{nframes} frames, FPS moyen ≈ {avg_fps:.1f}")

    if last is not None:
        bgr = cv2.cvtColor(last, cv2.COLOR_RGB2BGR)
        out = "/tmp/camera_test.jpg"
        cv2.imwrite(out, bgr)
        print(f"💾 Image sauvegardée: {out} ({bgr.shape[1]}x{bgr.shape[0]})")
    else:
        print("❌ Aucune image valide, rien à sauvegarder.")

    cam.close()
    print("✅ Caméra fermée")


if __name__ == "__main__":
    main()
