#!/bin/bash
# Simple Elisp-CI for testing
# Version: 1.0.0

set -e

VERSION="1.0.0"
PROJECT_ROOT="$(pwd)"

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

log() {
    local level=$1
    shift
    case $level in
        "INFO")  echo -e "${GREEN}[INFO]${NC}  $*" ;;
        "WARN")  echo -e "${YELLOW}[WARN]${NC}  $*" ;;
        "ERROR") echo -e "${RED}[ERROR]${NC} $*" ;;
    esac
}

analyze_project() {
    log "INFO" "Analyzing project: $(basename "$PROJECT_ROOT")"
    
    # Find elisp files
    local elisp_files=($(find . -maxdepth 2 -name "*.el" -not -path "./tests/*" 2>/dev/null || true))
    log "INFO" "Found ${#elisp_files[@]} Elisp files"
    
    # Find test files
    local test_files=($(find tests -name "test-*.el" 2>/dev/null || true))
    log "INFO" "Found ${#test_files[@]} test files"
    
    # Analyze requires
    if [[ ${#elisp_files[@]} -gt 0 ]]; then
        log "INFO" "External dependencies:"
        grep -h "^(require " "${elisp_files[@]}" 2>/dev/null | \
            sed "s/(require '\\([^)]*\\).*/  - \\1/" | \
            sort -u | head -10 || true
    fi
}

run_tests() {
    log "INFO" "Running ERT tests..."
    
    local test_files=($(find tests -name "test-*.el" 2>/dev/null || true))
    
    if [[ ${#test_files[@]} -eq 0 ]]; then
        log "ERROR" "No test files found"
        return 1
    fi
    
    local failed=0
    for test_file in "${test_files[@]}"; do
        log "INFO" "Testing: $test_file"
        
        if emacs -Q --batch \
            --eval "(add-to-list 'load-path \".\")" \
            --eval "(add-to-list 'load-path \"./etm-core\")" \
            --eval "(add-to-list 'load-path \"./etm-buffer\")" \
            --eval "(add-to-list 'load-path \"./etm-close\")" \
            --eval "(add-to-list 'load-path \"./etm-keys\")" \
            --eval "(add-to-list 'load-path \"./etm-layout\")" \
            --eval "(add-to-list 'load-path \"./etm-tabs\")" \
            --eval "(add-to-list 'load-path \"$(dirname "$test_file")\")" \
            --eval "(add-to-list 'load-path \"./tests/mocks\")" \
            --eval "(require 'ert)" \
            --eval "(load-file \"$test_file\")" \
            --eval "(ert-run-tests-batch-and-exit)" 2>/dev/null; then
            log "INFO" "✓ $test_file passed"
        else
            log "ERROR" "✗ $test_file failed"
            ((failed++))
        fi
    done
    
    if [[ $failed -eq 0 ]]; then
        log "INFO" "All tests passed!"
        return 0
    else
        log "ERROR" "$failed tests failed"
        return 1
    fi
}

case ${1:-help} in
    "analyze")
        analyze_project
        ;;
    "test")
        run_tests
        ;;
    "version")
        echo "elisp-ci-simple v$VERSION"
        ;;
    *)
        echo "Usage: elisp-ci-simple {analyze|test|version}"
        echo "  analyze - Analyze project structure"
        echo "  test    - Run all tests"
        echo "  version - Show version"
        ;;
esac