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

set -e

echo "======================================="
echo "SIMPLE DEBIAN BOOTC VALIDATION TEST"
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 ""

# Test our validation logic directly
echo "======================================="
echo "TEST 1: VALIDATE OUR DEBIAN PATCH LOGIC"
echo "======================================="

# Create a simple test Go program
cat > scripts/test-files/test_simple.go << 'EOF'
package main

import (
	"fmt"
	"os"
)

// Mock labels for testing
var testLabels = map[string]map[string]string{
	"redhat-bootc": {
		"com.redhat.bootc": "true",
		"ostree.bootable":  "true",
	},
	"debian-bootc": {
		"com.debian.bootc": "true",
		"ostree.bootable":  "true",
	},
	"both-labels": {
		"com.redhat.bootc": "true",
		"com.debian.bootc": "true",
		"ostree.bootable":  "true",
	},
	"no-bootc": {
		"some.other.label": "value",
	},
	"no-ostree": {
		"com.debian.bootc": "true",
	},
}

func isBootcImage(labels map[string]string) bool {
	// Check for Red Hat bootc label
	if val, exists := labels["com.redhat.bootc"]; exists && val == "true" {
		return true
	}
	
	// Check for Debian bootc label
	if val, exists := labels["com.debian.bootc"]; exists && val == "true" {
		return true
	}
	
	return false
}

func validateBootcImage(labels map[string]string, imageRef string) error {
	if !isBootcImage(labels) {
		return fmt.Errorf("image %s is not a bootc image (missing com.redhat.bootc=true or com.debian.bootc=true label)", imageRef)
	}
	
	// Check for required OSTree labels
	if val, exists := labels["ostree.bootable"]; !exists || val != "true" {
		return fmt.Errorf("image %s is not a bootc image (missing ostree.bootable=true label)", imageRef)
	}
	
	return nil
}

func getBootcType(labels map[string]string) string {
	if val, exists := labels["com.redhat.bootc"]; exists && val == "true" {
		return "redhat"
	}
	
	if val, exists := labels["com.debian.bootc"]; exists && val == "true" {
		return "debian"
	}
	
	return "unknown"
}

func main() {
	fmt.Println("Testing Debian bootc validation logic...")
	fmt.Println("")
	
	tests := []struct {
		name   string
		labels map[string]string
		expect bool
	}{
		{"Red Hat bootc", testLabels["redhat-bootc"], true},
		{"Debian bootc", testLabels["debian-bootc"], true},
		{"Both labels", testLabels["both-labels"], true},
		{"No bootc", testLabels["no-bootc"], false},
		{"No ostree", testLabels["no-ostree"], true}, // Should be true because it has bootc label
	}
	
	passed := 0
	total := len(tests)
	
	for _, test := range tests {
		fmt.Printf("Test: %s\n", test.name)
		fmt.Printf("Labels: %v\n", test.labels)
		
		isBootc := isBootcImage(test.labels)
		bootcType := getBootcType(test.labels)
		err := validateBootcImage(test.labels, "test-image")
		
		fmt.Printf("Is bootc: %t (expected: %t)\n", isBootc, test.expect)
		fmt.Printf("Bootc type: %s\n", bootcType)
		fmt.Printf("Validation error: %v\n", err)
		
		if isBootc == test.expect {
			fmt.Printf("✅ PASS\n")
			passed++
		} else {
			fmt.Printf("❌ FAIL\n")
		}
		fmt.Println("")
	}
	
	fmt.Printf("Test Results: %d/%d passed\n", passed, total)
	
	if passed == total {
		fmt.Println("🎉 All validation logic tests passed!")
		os.Exit(0)
	} else {
		fmt.Println("❌ Some validation logic tests failed")
		os.Exit(1)
	}
}
EOF

# Run the simple test
echo "Running validation logic test..."
if go run scripts/test-files/test_simple.go; then
    echo "✅ Validation logic test passed"
else
    echo "❌ Validation logic test failed"
    exit 1
fi

echo ""

# Test building minimal image only
echo "======================================="
echo "TEST 2: BUILD MINIMAL DEBIAN IMAGE"
echo "======================================="

echo "Building minimal Debian image..."
if podman build -f containerfiles/Containerfile.debian-trixie-minimal \
    -t localhost/particle-os-minimal:test .; then
    echo "✅ Successfully built minimal image"
    
    # Check the labels
    echo "Checking container labels..."
    echo "Labels for minimal image:"
    podman inspect localhost/particle-os-minimal:test \
        --format '{{range $k, $v := .Labels}}{{$k}}={{$v}}{{"\n"}}{{end}}' | \
        grep -E "(com\.(redhat|debian)\.bootc|ostree\.bootable)" || echo "No bootc labels found"
    echo ""
    
    # Test our validation logic with the real image
    echo "Testing validation logic with real image..."
    if go run scripts/test-files/test_validation.go localhost/particle-os-minimal:test; then
        echo "✅ Real image validation test passed"
    else
        echo "❌ Real image validation test failed"
        exit 1
    fi
else
    echo "❌ Failed to build minimal image"
    exit 1
fi

echo ""

# Test our Go build
echo "======================================="
echo "TEST 3: BUILD DEBIAN BOOTC-IMAGE-BUILDER"
echo "======================================="

echo "Building our Debian bootc-image-builder..."
cd bib
if go build -o ../bootc-image-builder ./cmd/bootc-image-builder/; then
    echo "✅ Successfully built bootc-image-builder"
    echo "Binary location: $WORK_DIR/bootc-image-builder"
else
    echo "❌ Failed to build bootc-image-builder"
    exit 1
fi

cd ..

echo ""

# Test our binary
echo "======================================="
echo "TEST 4: TEST BOOTC-IMAGE-BUILDER BINARY"
echo "======================================="

echo "Testing our bootc-image-builder binary..."
if ./bootc-image-builder --help; then
    echo "✅ bootc-image-builder binary works"
else
    echo "❌ bootc-image-builder binary failed"
    exit 1
fi

echo ""

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

echo "✅ Validation logic test passed"
echo "✅ Minimal image build test passed"
echo "✅ Real image validation test passed"
echo "✅ bootc-image-builder build test passed"
echo "✅ bootc-image-builder binary test passed"
echo ""

echo "🎉 All simple 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"
echo ""
echo "Next steps:"
echo "1. Free up disk space for full desktop image testing"
echo "2. Run ./scripts/phase5-start.sh for full Phase 5 testing"
echo "3. Test with real bootc-image-builder integration"
