#!/bin/bash

# Test script for apt-cacher-ng integration in particle-os
# This script tests the automatic detection and URL conversion features

set -euo pipefail

echo "🧪 Testing apt-cacher-ng integration in particle-os"
echo "=================================================="

# Configuration
APT_CACHER_NG_URL="${APT_CACHER_NG_URL:-http://192.168.1.101:3142}"
RECIPE_DIR="recipes"
BUILD_DIR="bib"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Helper functions
log_info() {
    echo -e "${BLUE}ℹ️  $1${NC}"
}

log_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

log_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

log_error() {
    echo -e "${RED}❌ $1${NC}"
}

# Test 1: Check if particle-os is built
test_particle_os_build() {
    log_info "Testing particle-os build..."
    
    if [ ! -f "$BUILD_DIR/particle-os" ]; then
        log_warning "particle-os not built, building now..."
        cd "$BUILD_DIR"
        if go build -o particle-os cmd/particle_os/main.go; then
            log_success "particle-os built successfully"
        else
            log_error "Failed to build particle-os"
            return 1
        fi
        cd ..
    else
        log_success "particle-os already built"
    fi
}

# Test 2: Test apt-cacher-ng connectivity
test_apt_cacher_ng_connectivity() {
    log_info "Testing apt-cacher-ng connectivity..."
    
    if curl -s --connect-timeout 5 --max-time 10 "$APT_CACHER_NG_URL" > /dev/null; then
        log_success "apt-cacher-ng is accessible at $APT_CACHER_NG_URL"
    else
        log_warning "apt-cacher-ng not accessible at $APT_CACHER_NG_URL"
        log_info "This is expected if apt-cacher-ng is not running"
    fi
}

# Test 3: Test recipe validation
test_recipe_validation() {
    log_info "Testing recipe validation..."
    
    local recipes=("corona" "apex" "euclase" "particle-os-base" "debian-test")
    local valid_count=0
    
    for recipe in "${recipes[@]}"; do
        if [ -f "$RECIPE_DIR/$recipe.yml" ]; then
            if "$BUILD_DIR/particle-os" validate "$RECIPE_DIR/$recipe.yml" > /dev/null 2>&1; then
                log_success "$recipe.yml is valid"
                ((valid_count++))
            else
                log_error "$recipe.yml validation failed"
            fi
        else
            log_warning "$recipe.yml not found"
        fi
    done
    
    log_info "Valid recipes: $valid_count/${#recipes[@]}"
}

# Test 4: Test apt-cacher-ng URL conversion
test_url_conversion() {
    log_info "Testing URL conversion logic..."
    
    # Test with environment variable set
    export APT_CACHER_NG_URL="$APT_CACHER_NG_URL"
    
    # Test a simple recipe build with verbose output
    if [ -f "$RECIPE_DIR/debian-test.yml" ]; then
        log_info "Testing debian-test recipe with apt-cacher-ng..."
        
        # Run with --dry-run if available, otherwise just validate
        if "$BUILD_DIR/particle-os" --help | grep -q "dry-run"; then
            "$BUILD_DIR/particle-os" build --dry-run --verbose "$RECIPE_DIR/debian-test.yml" 2>&1 | grep -i "apt-cacher-ng\|cache" || true
        else
            log_info "Running recipe validation to test URL conversion..."
            "$BUILD_DIR/particle-os" validate "$RECIPE_DIR/debian-test.yml"
        fi
        
        log_success "URL conversion test completed"
    else
        log_warning "debian-test.yml not found, skipping URL conversion test"
    fi
}

# Test 5: Test CI/CD features
test_cicd_features() {
    log_info "Testing CI/CD features..."
    
    # Test JSON output
    if "$BUILD_DIR/particle-os" --help | grep -q "json"; then
        log_success "JSON output support available"
    else
        log_warning "JSON output support not available"
    fi
    
    # Test quiet mode
    if "$BUILD_DIR/particle-os" --help | grep -q "quiet"; then
        log_success "Quiet mode support available"
    else
        log_warning "Quiet mode support not available"
    fi
    
    # Test clean mode
    if "$BUILD_DIR/particle-os" --help | grep -q "clean"; then
        log_success "Clean mode support available"
    else
        log_warning "Clean mode support not available"
    fi
}

# Test 6: Test environment variable handling
test_environment_variables() {
    log_info "Testing environment variable handling..."
    
    # Test APT_CACHER_NG_URL environment variable
    export APT_CACHER_NG_URL="http://test-cache:3142"
    
    if [ "$APT_CACHER_NG_URL" = "http://test-cache:3142" ]; then
        log_success "Environment variable APT_CACHER_NG_URL set correctly"
    else
        log_error "Failed to set APT_CACHER_NG_URL environment variable"
    fi
    
    # Reset to original value
    export APT_CACHER_NG_URL="http://192.168.1.101:3142"
}

# Test 7: Performance comparison (if possible)
test_performance() {
    log_info "Testing performance features..."
    
    # Check if we can measure build time
    if command -v time > /dev/null 2>&1; then
        log_success "Time measurement available"
        
        # Test recipe validation performance
        log_info "Measuring recipe validation performance..."
        time "$BUILD_DIR/particle-os" validate "$RECIPE_DIR/debian-test.yml" > /dev/null 2>&1
    else
        log_warning "Time measurement not available"
    fi
}

# Main test execution
main() {
    echo
    log_info "Starting apt-cacher-ng integration tests..."
    echo
    
    # Run all tests
    test_particle_os_build
    echo
    
    test_apt_cacher_ng_connectivity
    echo
    
    test_recipe_validation
    echo
    
    test_url_conversion
    echo
    
    test_cicd_features
    echo
    
    test_environment_variables
    echo
    
    test_performance
    echo
    
    # Summary
    echo "=================================================="
    log_success "apt-cacher-ng integration tests completed!"
    echo
    log_info "Next steps:"
    echo "1. Ensure apt-cacher-ng is running at $APT_CACHER_NG_URL"
    echo "2. Set APT_CACHER_NG_URL environment variable for CI/CD"
    echo "3. Test building images with: sudo ./bib/particle-os build recipes/corona.yml"
    echo "4. Monitor cache hit rates in apt-cacher-ng logs"
    echo
    log_info "For more information, see: docs/apt-cacher-ng-integration.md"
}

# Run main function
main "$@"
