#!/bin/bash
# TESTME.sh - Comprehensive testing script template
# Generated by supernal-code package

# Configuration
COVERAGE_THRESHOLD=80
PARALLEL_TESTS=true
RUN_E2E=false
VERBOSE=false
BAIL_ON_FAILURE=true

# Color definitions
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
NC='\033[0m'

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

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

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

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

log_info() {
    echo -e "${PURPLE}[INFO]${NC} $1"
}

# Test execution functions
run_unit_tests() {
    log_test "Running unit tests..."
    
    if [[ -f "package.json" ]]; then
        # Check for common test frameworks
        if npm run | grep -q "test:unit"; then
            log_info "Running npm run test:unit"
            npm run test:unit
        elif npm run | grep -q "test" && ! npm run | grep -q "test:"; then
            log_info "Running npm test"
            npm test
        elif command -v jest &> /dev/null; then
            log_info "Running jest"
            jest --testPathPattern="unit|spec" --coverage=false
        elif command -v mocha &> /dev/null; then
            log_info "Running mocha"
            mocha "test/**/*.spec.js" "test/**/*.test.js"
        else
            log_warning "No unit test framework detected"
            return 0
        fi
    else
        log_warning "No package.json found, skipping unit tests"
        return 0
    fi
    
    log_success "Unit tests completed"
}

run_integration_tests() {
    log_test "Running integration tests..."
    
    if [[ -f "package.json" ]] && npm run | grep -q "test:integration"; then
        log_info "Running npm run test:integration"
        npm run test:integration
    elif [[ -d "test/integration" ]] || [[ -d "tests/integration" ]]; then
        if command -v jest &> /dev/null; then
            log_info "Running jest integration tests"
            jest --testPathPattern="integration"
        elif command -v mocha &> /dev/null; then
            log_info "Running mocha integration tests"
            mocha "test/integration/**/*.js" "tests/integration/**/*.js"
        else
            log_warning "Integration test directory found but no test runner available"
            return 0
        fi
    else
        log_info "No integration tests found, skipping"
        return 0
    fi
    
    log_success "Integration tests completed"
}

run_e2e_tests() {
    if [[ "$RUN_E2E" == "true" ]]; then
        log_test "Running end-to-end tests..."
        
        if [[ -f "package.json" ]] && npm run | grep -q "test:e2e"; then
            log_info "Running npm run test:e2e"
            npm run test:e2e
        elif [[ -d "test/e2e" ]] || [[ -d "tests/e2e" ]]; then
            if command -v playwright &> /dev/null; then
                log_info "Running playwright e2e tests"
                playwright test
            elif command -v cypress &> /dev/null; then
                log_info "Running cypress e2e tests"
                cypress run
            else
                log_warning "E2E test directory found but no e2e runner available"
                return 0
            fi
        else
            log_info "No e2e tests found, skipping"
            return 0
        fi
        
        log_success "E2E tests completed"
    else
        log_info "E2E tests disabled, use --e2e to enable"
    fi
}

run_lint_checks() {
    log_test "Running code quality checks..."
    
    if [[ -f "package.json" ]]; then
        if npm run | grep -q "lint"; then
            log_info "Running npm run lint"
            npm run lint
        elif command -v eslint &> /dev/null && [[ -f ".eslintrc.js" || -f ".eslintrc.json" ]]; then
            log_info "Running eslint"
            eslint .
        else
            log_info "No linting configuration found, skipping"
            return 0
        fi
    fi
    
    log_success "Code quality checks completed"
}

check_coverage() {
    log_test "Checking test coverage..."
    
    if [[ -f "package.json" ]] && npm run | grep -q "test:coverage"; then
        log_info "Running npm run test:coverage"
        npm run test:coverage
    elif command -v jest &> /dev/null; then
        log_info "Running jest with coverage"
        jest --coverage --coverageThreshold="{'global':{'statements':$COVERAGE_THRESHOLD,'branches':$COVERAGE_THRESHOLD,'functions':$COVERAGE_THRESHOLD,'lines':$COVERAGE_THRESHOLD}}"
    elif command -v nyc &> /dev/null; then
        log_info "Running nyc coverage check"
        nyc --check-coverage --statements $COVERAGE_THRESHOLD --branches $COVERAGE_THRESHOLD --functions $COVERAGE_THRESHOLD --lines $COVERAGE_THRESHOLD npm test
    else
        log_warning "No coverage tool available, skipping coverage check"
        return 0
    fi
    
    log_success "Coverage requirements met"
}

run_security_checks() {
    log_test "Running security checks..."
    
    if [[ -f "package.json" ]]; then
        if npm run | grep -q "audit"; then
            log_info "Running npm run audit"
            npm run audit
        else
            log_info "Running npm audit"
            npm audit --audit-level=moderate
        fi
    else
        log_info "No package.json found, skipping security checks"
    fi
    
    log_success "Security checks completed"
}

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --coverage-threshold)
            COVERAGE_THRESHOLD="$2"
            shift 2
            ;;
        --e2e)
            RUN_E2E=true
            shift
            ;;
        --no-parallel)
            PARALLEL_TESTS=false
            shift
            ;;
        --verbose|-v)
            VERBOSE=true
            shift
            ;;
        --no-bail)
            BAIL_ON_FAILURE=false
            shift
            ;;
        --help|-h)
            echo "Usage: $0 [options]"
            echo "Options:"
            echo "  --coverage-threshold N  Set coverage threshold (default: 80)"
            echo "  --e2e                  Include end-to-end tests"
            echo "  --no-parallel          Disable parallel test execution"
            echo "  --verbose, -v          Enable verbose output"
            echo "  --no-bail              Continue testing after failures"
            echo "  --help, -h             Show this help message"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            echo "Use --help for usage information"
            exit 1
            ;;
    esac
done

# Configure error handling
if [[ "$BAIL_ON_FAILURE" == "true" ]]; then
    set -e
    trap 'log_failure "Tests failed"; exit 1' ERR
fi

# Main test execution
log_info "Starting comprehensive test suite..."
log_info "Coverage threshold: $COVERAGE_THRESHOLD%"
log_info "E2E tests: $([ "$RUN_E2E" == "true" ] && echo "enabled" || echo "disabled")"
log_info "Parallel execution: $([ "$PARALLEL_TESTS" == "true" ] && echo "enabled" || echo "disabled")"

# Run test suites
run_lint_checks
run_unit_tests
run_integration_tests
run_e2e_tests
check_coverage
run_security_checks

echo ""
log_success "✅ All tests completed successfully!"
log_info "Test suite finished at $(date)" 