#!/bin/bash
#
# Test Suite for Docker Compose Creator
# Validates templates and scripts
#

set -e

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

print_info() { echo -e "${BLUE}ℹ${NC} $1"; }
print_success() { echo -e "${GREEN}✓${NC} $1"; }
print_warning() { echo -e "${YELLOW}⚠${NC} $1"; }
print_error() { echo -e "${RED}✗${NC} $1"; }

# Test counters
TESTS_RUN=0
TESTS_PASSED=0
TESTS_FAILED=0

# Test directory
TEST_DIR="$(mktemp -d)"
trap "rm -rf $TEST_DIR" EXIT

# Locations
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PARENT_DIR="$(dirname "$SCRIPT_DIR")"
GENERATOR="$PARENT_DIR/scripts/generate-compose.sh"
VALIDATOR="$PARENT_DIR/scripts/validate-compose.sh"
TEMPLATES_DIR="$PARENT_DIR/templates"

echo
echo "========================================"
echo "  Docker Compose Creator Test Suite"
echo "========================================"
echo

# Test 1: Scripts exist
test_scripts_exist() {
    ((TESTS_RUN++))
    print_info "Test 1: Checking scripts..."

    if [[ ! -x "$GENERATOR" ]]; then
        print_error "Generator not found or not executable: $GENERATOR"
        ((TESTS_FAILED++))
        return 1
    fi

    if [[ ! -x "$VALIDATOR" ]]; then
        print_error "Validator not found or not executable: $VALIDATOR"
        ((TESTS_FAILED++))
        return 1
    fi

    print_success "Scripts exist and are executable"
    ((TESTS_PASSED++))
}

# Test 2: Templates exist
test_templates_exist() {
    ((TESTS_RUN++))
    print_info "Test 2: Checking templates..."

    REQUIRED_TEMPLATES=(
        "fullstack-web-app"
        "wordpress"
        "dev-environment"
        "microservices"
        "monitoring-stack"
    )

    for template in "${REQUIRED_TEMPLATES[@]}"; do
        if [[ ! -d "$TEMPLATES_DIR/$template" ]]; then
            print_error "Template not found: $template"
            ((TESTS_FAILED++))
            return 1
        fi

        if [[ ! -f "$TEMPLATES_DIR/$template/compose.yaml" ]]; then
            print_error "compose.yaml not found in $template"
            ((TESTS_FAILED++))
            return 1
        fi
    done

    print_success "All templates exist"
    ((TESTS_PASSED++))
}

# Test 3: Templates are valid YAML
test_template_syntax() {
    local template=$1
    ((TESTS_RUN++))
    print_info "Test 3.$template: Validating YAML syntax..."

    local compose_file="$TEMPLATES_DIR/$template/compose.yaml"

    if command -v python3 &> /dev/null; then
        if ! python3 -c "import yaml; yaml.safe_load(open('$compose_file'))" 2>/dev/null; then
            print_error "Invalid YAML syntax in $template"
            ((TESTS_FAILED++))
            return 1
        fi
    fi

    print_success "YAML syntax valid for $template"
    ((TESTS_PASSED++))
}

# Test 4: No version field (Compose v2)
test_no_version_field() {
    local template=$1
    ((TESTS_RUN++))
    print_info "Test 4.$template: Checking for version field..."

    local compose_file="$TEMPLATES_DIR/$template/compose.yaml"

    if grep -q "^version:" "$compose_file"; then
        print_warning "Template $template contains deprecated 'version' field"
        ((TESTS_PASSED++))  # Warning, not failure
    else
        print_success "No version field in $template (Compose v2 compliant)"
        ((TESTS_PASSED++))
    fi
}

# Test 5: Has health checks
test_healthchecks() {
    local template=$1
    ((TESTS_RUN++))
    print_info "Test 5.$template: Checking for health checks..."

    local compose_file="$TEMPLATES_DIR/$template/compose.yaml"

    if grep -q "healthcheck:" "$compose_file"; then
        print_success "Health checks found in $template"
        ((TESTS_PASSED++))
    else
        print_warning "No health checks in $template"
        ((TESTS_PASSED++))  # Warning
    fi
}

# Test 6: Has resource limits
test_resource_limits() {
    local template=$1
    ((TESTS_RUN++))
    print_info "Test 6.$template: Checking resource limits..."

    local compose_file="$TEMPLATES_DIR/$template/compose.yaml"

    if grep -q "resources:" "$compose_file" || grep -q "deploy:" "$compose_file"; then
        print_success "Resource limits found in $template"
        ((TESTS_PASSED++))
    else
        print_warning "No resource limits in $template"
        ((TESTS_PASSED++))  # Warning
    fi
}

# Test 7: Generator creates project
test_generator() {
    local template=$1
    ((TESTS_RUN++))
    print_info "Test 7.$template: Testing generator..."

    local project_name="test-$template"
    local output_path="$TEST_DIR/$project_name"

    if ! "$GENERATOR" -t "$template" -n "$project_name" -o "$TEST_DIR" > /dev/null 2>&1; then
        print_error "Generator failed for $template"
        ((TESTS_FAILED++))
        return 1
    fi

    if [[ ! -d "$output_path" ]]; then
        print_error "Output directory not created for $template"
        ((TESTS_FAILED++))
        return 1
    fi

    if [[ ! -f "$output_path/compose.yaml" ]]; then
        print_error "compose.yaml not created for $template"
        ((TESTS_FAILED++))
        return 1
    fi

    print_success "Generator works for $template"
    ((TESTS_PASSED++))
}

# Test 8: Validate with docker compose (if available)
test_docker_compose_validation() {
    local template=$1

    if ! command -v docker &> /dev/null; then
        print_info "Docker not installed, skipping compose validation"
        return 0
    fi

    if ! docker compose version &> /dev/null; then
        print_info "Docker Compose not available, skipping validation"
        return 0
    fi

    ((TESTS_RUN++))
    print_info "Test 8.$template: Docker Compose validation..."

    local compose_file="$TEMPLATES_DIR/$template/compose.yaml"
    cd "$TEMPLATES_DIR/$template"

    if docker compose -f compose.yaml config > /dev/null 2>&1; then
        print_success "Docker Compose validation passed for $template"
        ((TESTS_PASSED++))
    else
        print_error "Docker Compose validation failed for $template"
        ((TESTS_FAILED++))
        return 1
    fi
}

# Run tests
echo
print_info "Running test suite..."
echo

# Basic tests
test_scripts_exist
test_templates_exist

# Test each template
TEMPLATES=("fullstack-web-app" "wordpress" "dev-environment" "microservices" "monitoring-stack")

for template in "${TEMPLATES[@]}"; do
    echo
    print_info "Testing template: $template"
    echo

    test_template_syntax "$template"
    test_no_version_field "$template"
    test_healthchecks "$template"
    test_resource_limits "$template"
    test_generator "$template"
    test_docker_compose_validation "$template"
done

# Summary
echo
echo "========================================"
echo "  Test Summary"
echo "========================================"
echo
echo "Total tests run:    $TESTS_RUN"
print_success "Tests passed:     $TESTS_PASSED"
if [[ $TESTS_FAILED -gt 0 ]]; then
    print_error "Tests failed:     $TESTS_FAILED"
else
    print_success "Tests failed:     $TESTS_FAILED"
fi
echo

if [[ $TESTS_FAILED -eq 0 ]]; then
    print_success "All tests passed!"
    echo
    print_info "Docker Compose Creator is working correctly"
    exit 0
else
    print_error "Some tests failed"
    echo
    print_info "Please review the errors above"
    exit 1
fi
