fn current_controller_state_after_recovery() -> anyhow::Result<(String, String)> {
    #[cfg(coverage)]
    {
        if std::env::var("LESAVKA_TEST_RECOVERY_STATE_ERROR").is_ok() {
            anyhow::bail!("forced recovery state read failure");
        }
        if let Ok(state) = std::env::var("LESAVKA_TEST_RECOVERY_STATE") {
            return Ok(("coverage-ctrl".to_string(), state));
        }
    }
    UsbGadget::current_controller_state()
}

fn restart_uvc_helper() -> anyhow::Result<()> {
    #[cfg(coverage)]
    if let Ok(message) = std::env::var("LESAVKA_TEST_UVC_HELPER_RESTART_ERR") {
        anyhow::bail!("{message}");
    }
    if std::env::var("LESAVKA_GADGET_SYSFS_ROOT").is_ok()
        || std::env::var("LESAVKA_GADGET_CONFIGFS_ROOT").is_ok()
    {
        return Ok(());
    }

    run_systemctl(&["reset-failed", "lesavka-uvc.service"])?;
    match run_systemctl(&["restart", "lesavka-uvc.service"]) {
        Ok(()) => Ok(()),
        Err(err) if uvc_helper_restart_was_dependency_refused(&err.to_string()) => {
            warn!(
                "lesavka-uvc.service refused a direct restart because it is dependency-managed; USB reset already cycled the gadget"
            );
            Ok(())
        }
        Err(err) => Err(err),
    }
}

fn run_systemctl(args: &[&str]) -> anyhow::Result<()> {
    let output = Command::new("systemctl")
        .args(args)
        .output()
        .with_context(|| format!("running systemctl {}", args.join(" ")))?;
    if output.status.success() {
        return Ok(());
    }
    let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
    let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
    anyhow::bail!(
        "systemctl {} failed: {}{}",
        args.join(" "),
        if stderr.is_empty() {
            stdout.as_str()
        } else {
            stderr.as_str()
        },
        if stderr.is_empty() || stdout.is_empty() || stderr == stdout {
            ""
        } else {
            " / also see stdout"
        }
    );
}

fn uvc_helper_restart_was_dependency_refused(message: &str) -> bool {
    message.contains("Operation refused") || message.contains("may be requested by dependency only")
}
