use super::BuildahError;
use super::execute_buildah_command;
use crate::process::CommandResult;

/// Create a container from an image
pub fn from(image: &str) -> Result<CommandResult, BuildahError> {
    execute_buildah_command(&["from", image])
}

/// Run a command in a container
///
/// # Arguments
///
/// * `container` - The container ID or name
/// * `command` - The command to run
pub fn run(container: &str, command: &str) -> Result<CommandResult, BuildahError> {
    execute_buildah_command(&["run", container, "sh", "-c", command])
}

/// Run a command in a container with specified isolation
///
/// # Arguments
///
/// * `container` - The container ID or name
/// * `command` - The command to run
/// * `isolation` - Isolation method (e.g., "chroot", "rootless", "oci")
pub fn bah_run_with_isolation(
    container: &str,
    command: &str,
    isolation: &str,
) -> Result<CommandResult, BuildahError> {
    execute_buildah_command(&[
        "run",
        "--isolation",
        isolation,
        container,
        "sh",
        "-c",
        command,
    ])
}

/// Copy files into a container
pub fn bah_copy(container: &str, source: &str, dest: &str) -> Result<CommandResult, BuildahError> {
    execute_buildah_command(&["copy", container, source, dest])
}

pub fn bah_add(container: &str, source: &str, dest: &str) -> Result<CommandResult, BuildahError> {
    execute_buildah_command(&["add", container, source, dest])
}

/// Commit a container to an image
pub fn bah_commit(container: &str, image_name: &str) -> Result<CommandResult, BuildahError> {
    execute_buildah_command(&["commit", container, image_name])
}

/// Remove a container
pub fn bah_remove(container: &str) -> Result<CommandResult, BuildahError> {
    execute_buildah_command(&["rm", container])
}

/// List containers
pub fn bah_list() -> Result<CommandResult, BuildahError> {
    execute_buildah_command(&["containers"])
}

/// Build an image from a Containerfile/Dockerfile
///
/// # Arguments
///
/// * `tag` - Optional tag for the image (e.g., "my-app:latest")
/// * `context_dir` - The directory containing the Containerfile/Dockerfile (usually ".")
/// * `file` - Optional path to a specific Containerfile/Dockerfile
/// * `isolation` - Optional isolation method (e.g., "chroot", "rootless", "oci")
pub fn bah_build(
    tag: Option<&str>,
    context_dir: &str,
    file: &str,
    isolation: Option<&str>,
) -> Result<CommandResult, BuildahError> {
    let mut args = Vec::new();
    args.push("build");

    if let Some(tag_value) = tag {
        args.push("-t");
        args.push(tag_value);
    }

    if let Some(isolation_value) = isolation {
        args.push("--isolation");
        args.push(isolation_value);
    }

    args.push("-f");
    args.push(file);

    args.push(context_dir);

    execute_buildah_command(&args)
}
