use super::error::BtrfsError;
use super::cmd::filesystem_show_execute;
use std::fs;
use std::os::unix::fs::FileTypeExt;
use std::path::Path;

pub fn path_to_str(path: &Path) -> Result<&str, BtrfsError> {
    path.to_str()
        .ok_or_else(|| BtrfsError::InvalidPath(format!("Invalid path (not valid UTF-8): {:?}", path)))
}

pub fn ensure_block_device(path: &Path) -> Result<(), BtrfsError> {
    let path_str = path_to_str(path)?;
    
    let metadata = fs::metadata(path)
        .map_err(|e| BtrfsError::InvalidDevice(format!(
            "Failed to access device {}: {}",
            path_str, e
        )))?;

    if !metadata.file_type().is_block_device() {
        return Err(BtrfsError::InvalidDevice(format!(
            "Path {} is not a block device",
            path_str
        )));
    }

    Ok(())
}

pub fn ensure_btrfs(path: &Path) -> Result<(), BtrfsError> {
    let path_str = path_to_str(path)?;

    match filesystem_show_execute(path_str) {
        Ok(result) if result.success => Ok(()),
        Ok(_) => Err(BtrfsError::InvalidPath(format!(
            "Path {} is not on a Btrfs filesystem",
            path_str
        ))),
        Err(e) => Err(BtrfsError::InvalidPath(format!(
            "Failed to verify Btrfs filesystem at {}: {}",
            path_str, e
        ))),
    }
}
