#[cfg(not(coverage))]
fn active_leases(inner: &CapturePowerInner) -> u32 {
    inner.preview_leases.saturating_add(inner.session_leases)
}

#[cfg(not(coverage))]
fn desired_state_and_grace(inner: &CapturePowerInner, now: Instant) -> (bool, Option<Duration>) {
    if let Some(manual_override) = inner.manual_override {
        return (manual_override, None);
    }
    let grace_remaining = inner
        .session_grace_deadline
        .and_then(|deadline| deadline.checked_duration_since(now));
    let desired = inner.preview_leases > 0 || inner.session_leases > 0 || grace_remaining.is_some();
    (desired, grace_remaining)
}

#[cfg(not(coverage))]
fn capture_power_session_grace_from_env() -> Duration {
    std::env::var("LESAVKA_CAPTURE_POWER_GRACE_SECS")
        .ok()
        .and_then(|raw| raw.parse::<u64>().ok())
        .map(Duration::from_secs)
        .unwrap_or_else(|| Duration::from_secs(30))
}

#[cfg(not(coverage))]
async fn inspect_unit(unit: &str) -> Result<UnitSnapshot> {
    let unit = unit.to_string();
    tokio::task::spawn_blocking(move || inspect_unit_blocking(unit.as_str()))
        .await
        .map_err(|err| anyhow!("capture power inspect task failed: {err}"))?
}

#[cfg(not(coverage))]
fn inspect_unit_blocking(unit: &str) -> Result<UnitSnapshot> {
    if capture_power_unit_disabled(unit) {
        return Ok(UnitSnapshot {
            available: false,
            enabled: false,
            detail: "disabled".to_string(),
        });
    }

    let output = Command::new("systemctl")
        .args([
            "show",
            unit,
            "--property=LoadState,ActiveState,SubState",
            "--value",
        ])
        .output()
        .with_context(|| format!("querying systemd unit {unit}"))?;

    if !output.status.success() {
        return Err(anyhow!(
            "systemctl show {unit} failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        ));
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut lines = stdout.lines();
    let load_state = lines.next().unwrap_or_default().trim().to_string();
    let active_state = lines.next().unwrap_or_default().trim().to_string();
    let sub_state = lines.next().unwrap_or_default().trim().to_string();
    let available = !load_state.is_empty() && load_state != "not-found";
    let enabled = active_state == "active";
    let detail = if available {
        format!("{active_state}/{sub_state}")
    } else {
        "unit not found".to_string()
    };

    Ok(UnitSnapshot {
        available,
        enabled,
        detail,
    })
}

#[cfg(not(coverage))]
async fn sync_unit_state(unit: &str, enabled: bool) -> Result<()> {
    let unit = unit.to_string();
    tokio::task::spawn_blocking(move || sync_unit_state_blocking(unit.as_str(), enabled))
        .await
        .map_err(|err| anyhow!("capture power sync task failed: {err}"))?
}

#[cfg(not(coverage))]
fn sync_unit_state_blocking(unit: &str, enabled: bool) -> Result<()> {
    if capture_power_unit_disabled(unit) {
        return Ok(());
    }

    let action = if enabled { "start" } else { "stop" };
    let status = Command::new("systemctl")
        .args([action, unit])
        .status()
        .with_context(|| format!("running systemctl {action} {unit}"))?;
    if status.success() {
        Ok(())
    } else {
        Err(anyhow!("systemctl {action} {unit} failed with {status}"))
    }
}

#[cfg(not(coverage))]
fn capture_power_unit_disabled(unit: &str) -> bool {
    matches!(
        unit.trim().to_ascii_lowercase().as_str(),
        "0" | "off" | "none" | "disabled"
    )
}

#[cfg(coverage)]
#[derive(Debug, Clone, Default)]
pub struct CapturePowerManager;

#[cfg(coverage)]
#[derive(Clone, Default)]
pub struct CapturePowerLease;

#[cfg(coverage)]
impl CapturePowerManager {
    pub fn new() -> Self {
        Self
    }

    pub async fn acquire(&self) -> CapturePowerLease {
        CapturePowerLease
    }

    pub async fn acquire_session(&self) -> CapturePowerLease {
        CapturePowerLease
    }

    pub async fn set_manual(&self, enabled: bool) -> anyhow::Result<CapturePowerState> {
        Ok(CapturePowerState {
            available: true,
            enabled,
            unit: "relay.service".to_string(),
            detail: if enabled {
                "active/running".to_string()
            } else {
                "inactive/dead".to_string()
            },
            active_leases: 0,
            mode: if enabled {
                "forced-on".to_string()
            } else {
                "forced-off".to_string()
            },
            detected_devices: 0,
        })
    }

    pub async fn set_auto(&self) -> anyhow::Result<CapturePowerState> {
        Ok(CapturePowerState {
            available: true,
            enabled: false,
            unit: "relay.service".to_string(),
            detail: "inactive/dead".to_string(),
            active_leases: 0,
            mode: "auto".to_string(),
            detected_devices: 0,
        })
    }

    pub async fn snapshot(&self) -> anyhow::Result<CapturePowerState> {
        Ok(CapturePowerState {
            available: true,
            enabled: false,
            unit: "relay.service".to_string(),
            detail: "inactive/dead".to_string(),
            active_leases: 0,
            mode: "auto".to_string(),
            detected_devices: 0,
        })
    }
}
