#!/bin/bash

# Script de test pour valider VEZA-FLOW
# Vérifie que tous les composants fonctionnent correctement

set -e

# Couleurs pour l'affichage
BLUE='\033[0;34m'
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

log_info() {
    echo -e "${BLUE}[TEST]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[PASS]${NC} $1"
}

log_error() {
    echo -e "${RED}[FAIL]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

# Configuration
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

# Tests à effectuer
test_files_exist() {
    log_info "Testing file existence..."
    
    local files=(
        "scripts/veza-cli.sh"
        "scripts/sync-cursor.py"
        ".veza/feature-manifest.yaml"
        ".cursor/settings.json"
        ".cursor/context.json"
        ".cursor/prompts.yaml"
        ".git/hooks/pre-commit"
        "README_VEZA_FLOW.md"
    )
    
    for file in "${files[@]}"; do
        if [[ -f "$PROJECT_ROOT/$file" ]]; then
            log_success "File exists: $file"
        else
            log_error "File missing: $file"
            return 1
        fi
    done
}

test_cli_functionality() {
    log_info "Testing CLI functionality..."
    
    # Test help command
    if ./scripts/veza-cli.sh help &> /dev/null; then
        log_success "CLI help command works"
    else
        log_error "CLI help command failed"
        return 1
    fi
    
    # Test commit validation
    if ./scripts/veza-cli.sh commit-validate "[core][feat] Test feature" &> /dev/null; then
        log_success "Commit validation works"
    else
        log_error "Commit validation failed"
        return 1
    fi
    
    # Test invalid commit format
    if ! ./scripts/veza-cli.sh commit-validate "invalid commit" &> /dev/null; then
        log_success "Invalid commit format correctly rejected"
    else
        log_error "Invalid commit format not rejected"
        return 1
    fi
}

test_sync_cursor() {
    log_info "Testing Cursor sync..."
    
    if python3 scripts/sync-cursor.py &> /dev/null; then
        log_success "Cursor sync works"
    else
        log_error "Cursor sync failed"
        return 1
    fi
}

test_manifest_structure() {
    log_info "Testing manifest structure..."
    
    if [[ -f "$PROJECT_ROOT/.veza/feature-manifest.yaml" ]]; then
        # Vérifier que le manifeste contient les sections essentielles
        if grep -q "features:" "$PROJECT_ROOT/.veza/feature-manifest.yaml" && \
           grep -q "compatibility_matrix:" "$PROJECT_ROOT/.veza/feature-manifest.yaml"; then
            log_success "Manifest structure is valid"
        else
            log_error "Manifest structure is invalid"
            return 1
        fi
    else
        log_error "Manifest file not found"
        return 1
    fi
}

test_git_hooks() {
    log_info "Testing Git hooks..."
    
    if [[ -x "$PROJECT_ROOT/.git/hooks/pre-commit" ]]; then
        log_success "Pre-commit hook is executable"
    else
        log_error "Pre-commit hook is not executable"
        return 1
    fi
}

test_cursor_config() {
    log_info "Testing Cursor configuration..."
    
    local config_files=(
        ".cursor/settings.json"
        ".cursor/context.json"
        ".cursor/prompts.yaml"
    )
    
    for file in "${config_files[@]}"; do
        if [[ -f "$PROJECT_ROOT/$file" ]]; then
            log_success "Cursor config exists: $file"
        else
            log_error "Cursor config missing: $file"
            return 1
        fi
    done
}

test_feature_creation() {
    log_info "Testing feature creation..."
    
    # Créer une feature de test
    if ./scripts/veza-cli.sh new feature test-feature &> /dev/null; then
        log_success "Feature creation works"
        
        # Vérifier que la structure a été créée
        if [[ -d "$PROJECT_ROOT/features/test-feature" ]]; then
            log_success "Feature directory created"
            
            # Nettoyer
            rm -rf "$PROJECT_ROOT/features/test-feature"
        else
            log_error "Feature directory not created"
            return 1
        fi
    else
        log_error "Feature creation failed"
        return 1
    fi
}

# Fonction principale de test
main() {
    echo "🧪 Testing VEZA-FLOW implementation..."
    echo "======================================"
    
    local tests=(
        "test_files_exist"
        "test_cli_functionality"
        "test_sync_cursor"
        "test_manifest_structure"
        "test_git_hooks"
        "test_cursor_config"
        "test_feature_creation"
    )
    
    local passed=0
    local failed=0
    
    for test in "${tests[@]}"; do
        if $test; then
            ((passed++))
        else
            ((failed++))
        fi
        echo ""
    done
    
    echo "======================================"
    echo "📊 Test Results:"
    echo "✅ Passed: $passed"
    echo "❌ Failed: $failed"
    echo "📈 Success Rate: $(( (passed * 100) / (passed + failed) ))%"
    
    if [[ $failed -eq 0 ]]; then
        echo ""
        echo "🎉 All tests passed! VEZA-FLOW is ready to use."
        echo ""
        echo "Next steps:"
        echo "1. Run: ./scripts/sync-cursor.py"
        echo "2. Start developing with: ./scripts/veza-cli.sh new feature <name>"
        echo "3. Follow the format: [SCOPE][TYPE] Description"
        exit 0
    else
        echo ""
        echo "⚠️  Some tests failed. Please check the implementation."
        exit 1
    fi
}

# Exécuter les tests
main "$@" 