// Test camera capture with colorspace conversion
var camera = use('camera');
var surface = use('sdl3/surface');
var json = use('json');

// Get first camera
var cameras = camera.list();
if (cameras.length == 0) {
  log.console("No cameras found!");
  $stop();
}

var cam_id = cameras[0];
log.console("Using camera:", camera.name(cam_id));

// Open camera with default settings
var cam = camera.open(cam_id);
if (!cam) {
  log.console("Failed to open camera!");
  $stop();
}

// Get the format being used
var format = cam.get_format();
log.console("\nCamera format:");
log.console("  Resolution:", format.width + "x" + format.height);
log.console("  Pixel format:", format.format);
log.console("  Colorspace:", format.colorspace);

// Handle camera approval
var approved = false;
$receiver(e => {
  if (e.type == 'camera_device_approved') {
    log.console("\nCamera approved!");
    approved = true;
  } else if (e.type == 'camera_device_denied') {
    log.error("Camera access denied!");
    $stop();
  }
});

// Wait for approval then capture
function capture_test() {
  if (!approved) {
    $delay(capture_test, 0.1);
    return;
  }
  
  log.console("\nCapturing frame...");
  var surf = cam.capture();
  
  if (!surf) {
    log.console("No frame captured yet, retrying...");
    $delay(capture_test, 0.1);
    return;
  }
  
  log.console("\nCaptured surface:");
  log.console("  Size:", surf.width + "x" + surf.height);
  log.console("  Format:", surf.format);
  
  // Test various colorspace conversions
  log.console("\nTesting colorspace conversions:");
  
  // Convert to sRGB if not already
  if (format.colorspace != "srgb") {
    try {
      var srgb_surf = surf.convert(surf.format, "srgb");
      log.console("  Converted to sRGB colorspace");
    } catch(e) {
      log.console("  sRGB conversion failed:", e.message);
    }
  }
  
  // Convert to linear sRGB for processing
  try {
    var linear_surf = surf.convert("rgba8888", "srgb_linear");
    log.console("  Converted to linear sRGB (RGBA8888) for processing");
  } catch(e) {
    log.console("  Linear sRGB conversion failed:", e.message);
  }
  
  // Convert to JPEG colorspace (common for compression)
  try {
    var jpeg_surf = surf.convert("rgb888", "jpeg");
    log.console("  Converted to JPEG colorspace (RGB888) for compression");
  } catch(e) {
    log.console("  JPEG colorspace conversion failed:", e.message);
  }
  
  // If YUV format, try BT.709 (HD video standard)
  if (surf.format.indexOf("yuv") != -1 || surf.format.indexOf("yuy") != -1) {
    try {
      var hd_surf = surf.convert(surf.format, "bt709_limited");
      log.console("  Converted to BT.709 limited (HD video standard)");
    } catch(e) {
      log.console("  BT.709 conversion failed:", e.message);
    }
  }
  
  log.console("\nTest complete!");
  $stop();
}

// Start capture test after a short delay
$delay(capture_test, 0.5);