#!/usr/bin/env herodo
// 02_image_operations.rhai
// Tests for Buildah image operations

// Custom assert function
fn assert_true(condition, message) {
    if !condition {
        print(`ASSERTION FAILED: ${message}`);
        throw message;
    }
}

// Custom assert_eq function
fn assert_eq(actual, expected, message) {
    if actual != expected {
        print(`ASSERTION FAILED: ${message}`);
        print(`Expected: "${expected}"`);
        print(`Actual: "${actual}"`);
        throw message;
    }
}

// Helper function to check if buildah is available
fn is_buildah_available() {
    try {
        let result = run("which buildah");
        return result.success;
    } catch(err) {
        return false;
    }
}

// Helper function to check if an image exists
fn image_exists(image_name) {
    try {
        let result = run(`buildah images -q ${image_name}`);
        return result.success && result.stdout.trim() != "";
    } catch(err) {
        return false;
    }
}

print("=== Testing Buildah Image Operations ===");

// Check if buildah is available
let buildah_available = is_buildah_available();
if !buildah_available {
    print("Buildah is not available. Skipping Buildah tests.");
    // Exit gracefully without error
    return;
}

print("✓ Buildah is available");

// Create a temporary directory for testing
let test_dir = "rhai_test_buildah";
mkdir(test_dir);

try {
    // Create a builder for testing
    let builder = bah_new("rhai_test_container", "alpine:latest");
    
    // Enable debug mode
    builder.debug_mode = true;
    
    // Test image_pull
    print("Testing image_pull()...");
    // Use a small image for testing
    let pull_result = builder.image_pull("alpine:3.14", true);
    assert_true(pull_result.success, "Image pull should succeed");
    print("✓ image_pull(): Image pulled successfully");
    
    // Test image_tag
    print("Testing image_tag()...");
    let tag_result = builder.image_tag("alpine:3.14", "rhai_test_tag:latest");
    assert_true(tag_result.success, "Image tag should succeed");
    print("✓ image_tag(): Image tagged successfully");
    
    // Test images (list)
    print("Testing images()...");
    let images = builder.images();
    assert_true(images.len() > 0, "There should be at least one image");
    
    // Find our tagged image
    let found_tag = false;
    for image in images {
        if image.names.contains("rhai_test_tag:latest") {
            found_tag = true;
            break;
        }
    }
    assert_true(found_tag, "Tagged image should be in the list");
    print("✓ images(): Images listed successfully");
    
    // Test build
    print("Testing build()...");
    
    // Create a simple Dockerfile
    let dockerfile_content = `FROM alpine:latest
RUN echo "Hello from Dockerfile" > /hello.txt
CMD ["cat", "/hello.txt"]
`;
    file_write(`${test_dir}/Dockerfile`, dockerfile_content);
    
    // Build the image
    let build_result = builder.build("rhai_test_build:latest", test_dir, "Dockerfile", "oci");
    assert_true(build_result.success, "Image build should succeed");
    print("✓ build(): Image built successfully");
    
    // Verify the built image exists
    assert_true(image_exists("rhai_test_build:latest"), "Built image should exist");
    
    // Test image_remove
    print("Testing image_remove()...");
    
    // Remove the tagged image
    let remove_tag_result = builder.image_remove("rhai_test_tag:latest");
    assert_true(remove_tag_result.success, "Image removal should succeed");
    print("✓ image_remove(): Tagged image removed successfully");
    
    // Remove the built image
    let remove_build_result = builder.image_remove("rhai_test_build:latest");
    assert_true(remove_build_result.success, "Image removal should succeed");
    print("✓ image_remove(): Built image removed successfully");
    
    // Clean up
    builder.remove();
    print("✓ Cleanup: Container removed");
    
    print("All image operations tests completed successfully!");
} catch(err) {
    print(`Error: ${err}`);
    
    // Clean up in case of error
    try {
        // Remove test container if it exists
        run("buildah rm rhai_test_container");
    } catch(_) {}
    
    try {
        // Remove test images if they exist
        run("buildah rmi rhai_test_tag:latest");
        run("buildah rmi rhai_test_build:latest");
    } catch(_) {}
    
    throw err;
} finally {
    // Clean up test directory
    delete(test_dir);
    print("✓ Cleanup: Test directory removed");
}
