// Basic buildah operations for container management
use super::BuildahError;
use crate::process::CommandResult;
use std::process::Command;

/// Execute a buildah command and return the result
///
/// # Arguments
///
/// * `args` - The command arguments
///
/// # Returns
///
/// * `Result<CommandResult, BuildahError>` - Command result or error
pub fn execute_buildah_command(args: &[&str]) -> Result<CommandResult, BuildahError> {
    // Get the debug flag from thread-local storage
    let debug = thread_local_debug();

    if debug {
        println!("Executing buildah command: buildah {}", args.join(" "));
    }

    let output = Command::new("buildah").args(args).output();

    match output {
        Ok(output) => {
            let stdout = String::from_utf8_lossy(&output.stdout).to_string();
            let stderr = String::from_utf8_lossy(&output.stderr).to_string();

            let result = CommandResult {
                stdout,
                stderr,
                success: output.status.success(),
                code: output.status.code().unwrap_or(-1),
            };

            // Always output stdout/stderr when debug is true
            if debug {
                if !result.stdout.is_empty() {
                    println!("Command stdout: {}", result.stdout);
                }

                if !result.stderr.is_empty() {
                    println!("Command stderr: {}", result.stderr);
                }

                if result.success {
                    println!("Command succeeded with code {}", result.code);
                } else {
                    println!("Command failed with code {}", result.code);
                }
            }

            if result.success {
                Ok(result)
            } else {
                // If command failed and debug is false, output stderr
                if !debug {
                    println!(
                        "Command failed with code {}: {}",
                        result.code,
                        result.stderr.trim()
                    );
                }
                Err(BuildahError::CommandFailed(format!(
                    "Command failed with code {}: {}",
                    result.code,
                    result.stderr.trim()
                )))
            }
        }
        Err(e) => {
            // Always output error information
            println!("Command execution failed: {}", e);
            Err(BuildahError::CommandExecutionFailed(e))
        }
    }
}

// Thread-local storage for debug flag
thread_local! {
    static DEBUG: std::cell::RefCell<bool> = std::cell::RefCell::new(false);
}

/// Set the debug flag for the current thread
pub fn set_thread_local_debug(debug: bool) {
    DEBUG.with(|cell| {
        *cell.borrow_mut() = debug;
    });
}

/// Get the debug flag for the current thread
pub fn thread_local_debug() -> bool {
    DEBUG.with(|cell| *cell.borrow())
}

// This function is no longer needed as the debug functionality is now integrated into execute_buildah_command
