use super::exec::execute_btrfs_command;
use super::super::error::BtrfsError;
use super::super::types::SubvolumeInfo;
use crate::process::CommandResult;
use std::path::Path;

pub fn execute(path: &str) -> Result<CommandResult, BtrfsError> {
    execute_btrfs_command(&["subvolume", "show", path])
}

pub fn parse(output: &str, path: &Path) -> Result<SubvolumeInfo, BtrfsError> {
    let mut lines = output.lines();
    let name = lines.next()
        .ok_or_else(|| BtrfsError::ParseError("Missing subvolume name in output".to_string()))?
        .trim()
        .to_string();

    let mut id = None;
    let mut uuid = None;
    let mut parent_id = None;
    let mut top_level_id = None;
    let mut generation = None;
    let mut gen_at_creation = None;
    let mut creation_time = None;

    for line in lines {
        let line = line.trim();
        if line.is_empty() || line.ends_with(':') {
            continue;
        }
        
        if let Some((key, value)) = line.split_once(':') {
            let key = key.trim();
            let value = value.trim();
            
            if value.is_empty() || value == "-" {
                continue;
            }

            match key {
                "Subvolume ID" => {
                    id = value.parse().ok();
                }
                "UUID" => {
                    uuid = Some(value.to_string());
                }
                "Parent ID" => {
                    parent_id = value.parse().ok();
                }
                "Top level ID" => {
                    top_level_id = value.parse().ok();
                }
                "Generation" => {
                    generation = value.parse().ok();
                }
                "Gen at creation" => {
                    gen_at_creation = value.parse().ok();
                }
                "Creation time" => {
                    creation_time = Some(value.to_string());
                }
                _ => {}
            }
        }
    }
    
    let id = id.ok_or_else(|| BtrfsError::ParseError("Missing Subvolume ID in output".to_string()))?;
    let top_level_id = top_level_id.unwrap_or(id);
    let generation = generation.ok_or_else(|| BtrfsError::ParseError("Missing Generation in output".to_string()))?;

    Ok(SubvolumeInfo {
        id,
        path: path.to_path_buf(),
        name,
        uuid,
        parent_id,
        top_level_id,
        generation,
        gen_at_creation,
        creation_time,
    })
}

pub fn execute_and_parse(path: &str) -> Result<SubvolumeInfo, BtrfsError> {
    let path_buf = std::path::PathBuf::from(path);
    let result = execute(path)?;
    parse(&result.stdout, &path_buf)
}

