#!/bin/bash
# Test Debian Validation Script
# Location: /home/joe/bootc-image-builder/debian-bootc-image-builder/scripts/test-debian-validation.sh

set -e

echo "======================================="
echo "TESTING DEBIAN BOOTC VALIDATION"
echo "======================================="

WORK_DIR="/home/joe/bootc-image-builder/debian-bootc-image-builder"
cd "$WORK_DIR"

echo "Working directory: $WORK_DIR"
echo ""

# Function to check if command exists
check_command() {
    if ! command -v "$1" &> /dev/null; then
        echo "ERROR: $1 is not installed or not in PATH"
        exit 1
    fi
}

# Check prerequisites
echo "Checking prerequisites..."
check_command podman
check_command go
echo "✅ All prerequisites found"
echo ""

# Function to build and test container image
test_container_validation() {
    local containerfile="$1"
    local tag="$2"
    local description="$3"
    
    echo "Testing $description..."
    echo "Containerfile: $containerfile"
    echo "Tag: $tag"
    echo ""
    
    # Build the container image
    echo "Building container image..."
    if ! podman build -f "$containerfile" -t "$tag" .; then
        echo "❌ Failed to build $tag"
        return 1
    fi
    echo "✅ Successfully built $tag"
    echo ""
    
    # Check the labels
    echo "Checking container labels..."
    echo "Labels for $tag:"
    podman inspect "$tag" --format '{{range $k, $v := .Labels}}{{$k}}={{$v}}{{"\n"}}{{end}}' | grep -E "(com\.(redhat|debian)\.bootc|ostree\.bootable)" || echo "No bootc labels found"
    echo ""
    
    # Test bootc container lint
    echo "Testing bootc container lint..."
    if podman run --rm "$tag" bash -c "bootc container lint 2>/dev/null || echo 'bootc not available in container'"; then
        echo "✅ bootc container lint passed or bootc not available"
    else
        echo "⚠️  bootc container lint failed (expected if bootc not installed)"
    fi
    echo ""
    
    # Test our validation logic
    echo "Testing our Debian validation logic..."
    if go run bib/internal/debian-patch/test_validation.go "$tag"; then
        echo "✅ Debian validation logic test passed"
    else
        echo "❌ Debian validation logic test failed"
        return 1
    fi
    echo ""
    
    return 0
}

# Create a simple test for our validation logic
cat > bib/internal/debian-patch/test_validation.go << 'EOF'
package main

import (
	"encoding/json"
	"fmt"
	"os"
	"os/exec"
	"strings"
)

type ContainerInspect struct {
	Labels map[string]string `json:"Labels"`
}

func main() {
	if len(os.Args) != 2 {
		fmt.Println("Usage: go run test_validation.go <image-tag>")
		os.Exit(1)
	}
	
	imageTag := os.Args[1]
	
	// Inspect the container image
	cmd := exec.Command("podman", "inspect", imageTag)
	output, err := cmd.Output()
	if err != nil {
		fmt.Printf("Error inspecting image %s: %v\n", imageTag, err)
		os.Exit(1)
	}
	
	// Parse the JSON output
	var containers []ContainerInspect
	if err := json.Unmarshal(output, &containers); err != nil {
		fmt.Printf("Error parsing JSON: %v\n", err)
		os.Exit(1)
	}
	
	if len(containers) == 0 {
		fmt.Printf("No container information found for %s\n", imageTag)
		os.Exit(1)
	}
	
	labels := containers[0].Labels
	fmt.Printf("Image: %s\n", imageTag)
	fmt.Printf("Labels: %v\n", labels)
	
	// Test our validation logic
	isBootc := false
	bootcType := "unknown"
	
	if val, exists := labels["com.redhat.bootc"]; exists && val == "true" {
		isBootc = true
		bootcType = "redhat"
	}
	
	if val, exists := labels["com.debian.bootc"]; exists && val == "true" {
		isBootc = true
		bootcType = "debian"
	}
	
	hasOstreeBootable := false
	if val, exists := labels["ostree.bootable"]; exists && val == "true" {
		hasOstreeBootable = true
	}
	
	fmt.Printf("Is bootc image: %t\n", isBootc)
	fmt.Printf("Bootc type: %s\n", bootcType)
	fmt.Printf("Has ostree.bootable: %t\n", hasOstreeBootable)
	
	if isBootc && hasOstreeBootable {
		fmt.Printf("✅ Image %s is a valid bootc image\n", imageTag)
		if bootcType == "debian" {
			fmt.Printf("✅ Image %s is specifically a Debian bootc image\n", imageTag)
		}
	} else {
		fmt.Printf("❌ Image %s is not a valid bootc image\n", imageTag)
		os.Exit(1)
	}
}
EOF

# Test minimal image
echo "======================================="
echo "TEST 1: MINIMAL DEBIAN IMAGE"
echo "======================================="

TEST_SUCCESS=0
TEST_TOTAL=0

TEST_TOTAL=$((TEST_TOTAL + 1))
if test_container_validation "containerfiles/Containerfile.debian-trixie-minimal" \
                           "localhost/particle-os-minimal:test" \
                           "Particle OS Minimal (Debian Trixie)"; then
    TEST_SUCCESS=$((TEST_SUCCESS + 1))
fi

echo "======================================="

# Test KDE image
echo "======================================="
echo "TEST 2: KDE DEBIAN IMAGE"
echo "======================================="

TEST_TOTAL=$((TEST_TOTAL + 1))
if test_container_validation "containerfiles/Containerfile.debian-trixie-kde" \
                           "localhost/particle-os-kde:test" \
                           "Particle OS KDE (Debian Trixie)"; then
    TEST_SUCCESS=$((TEST_SUCCESS + 1))
fi

echo "======================================="
echo "TESTING SUMMARY"
echo "======================================="

echo "Test Results: $TEST_SUCCESS/$TEST_TOTAL successful"
echo ""

if [ $TEST_SUCCESS -eq $TEST_TOTAL ]; then
    echo "🎉 All Debian validation tests passed!"
    echo "✅ Our Debian fork now recognizes com.debian.bootc=true labels"
    echo "✅ Ready to proceed with Phase 5 real image testing"
    exit 0
else
    echo "❌ Some Debian validation tests failed"
    echo "⚠️  Check the logs above for details"
    exit 1
fi
