/// Runs only the coverage-mode startup probes and refuses the live control loop.
///
/// Inputs: CLI/env device settings. Output: successful validation until the
/// disabled loop guard. Why: contracts need startup coverage without driving USB.
fn main() -> Result<()> {
    let (dev, _cfg) = parse_args()?;
    let _ = load_interfaces();
    let _ = UvcConfig::from_env();

    let _ = open_with_retry(&dev)?;
    anyhow::bail!("coverage harness: control loop disabled");
}

#[cfg(coverage)]
fn parse_args() -> Result<(String, UvcConfig)> {
    let args: Vec<String> = env::args().skip(1).collect();
    let dev = parse_device_arg(&args)
        .or_else(|| env::var("LESAVKA_UVC_DEV").ok())
        .context("missing --device (or LESAVKA_UVC_DEV)")?;

    Ok((dev, UvcConfig::from_env()))
}

#[cfg(coverage)]
/// Finds the UVC device from `--device`, `-d`, or a positional path argument.
///
/// Inputs: raw CLI arguments. Output: the selected device path when present.
/// Why: manual probes and contract tests both exercise the same device syntax.
fn parse_device_arg(args: &[String]) -> Option<String> {
    args
        .windows(2)
        .find_map(|pair| (pair[0] == "--device" || pair[0] == "-d").then(|| pair[1].clone()))
        .or_else(|| {
            args.iter()
                .rev()
                .find(|arg| {
                    arg.as_str() != "--device" && arg.as_str() != "-d" && arg.starts_with('/')
                })
                .cloned()
        })
}

#[cfg(coverage)]
/// Opens the UVC control device with safe coverage defaults.
///
/// Inputs: device path and read/write env knobs. Output: opened file handle.
/// Why: tests should default to non-blocking read-only access unless opted in.
fn open_with_retry(path: &str) -> Result<std::fs::File> {
    let read_only = uvc_control_read_only();
    let mut opts = OpenOptions::new();
    opts.read(true);
    if !read_only {
        opts.write(true);
    }
    if env::var("LESAVKA_UVC_BLOCKING").is_err() {
        opts.custom_flags(libc::O_NONBLOCK);
    }
    opts.open(path).with_context(|| format!("open {path}"))
}

#[cfg(coverage)]
/// Keep coverage-mode UVC control opens read-only unless a test opts into writes.
fn uvc_control_read_only() -> bool {
    env::var("LESAVKA_UVC_CONTROL_READ_ONLY")
        .ok()
        .map(|value| {
            let trimmed = value.trim();
            !(trimmed.eq_ignore_ascii_case("0")
                || trimmed.eq_ignore_ascii_case("false")
                || trimmed.eq_ignore_ascii_case("no")
                || trimmed.eq_ignore_ascii_case("off"))
        })
        .unwrap_or(true)
}
