#!/usr/bin/env bash
# Lint all Lux example and project files
# Run this before committing to catch parse/type errors early

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT_DIR="$(dirname "$SCRIPT_DIR")"
LUX="${ROOT_DIR}/target/release/lux"

# Build if needed
if [ ! -f "$LUX" ]; then
    echo "Building lux..."
    cd "$ROOT_DIR" && cargo build --release
fi

FAILED=0
PASSED=0

check_file() {
    local file="$1"
    local output
    # Run the file and capture output, timeout after 10s
    if output=$(timeout 10 "$LUX" "$file" 2>&1); then
        echo -e "${GREEN}OK${NC}: $file"
        ((PASSED++)) || true
    else
        # Check if it's just a runtime error vs parse/type error
        if echo "$output" | grep -q "Parse error\|Type error\|Type Error\|Type Mismatch"; then
            echo -e "${RED}FAIL${NC}: $file"
            echo "$output" | head -20
            echo ""
            ((FAILED++)) || true
        else
            # Runtime errors are OK for linting (file parses and type checks)
            echo -e "${GREEN}OK${NC}: $file (runtime error expected)"
            ((PASSED++)) || true
        fi
    fi
}

echo "=== Linting Lux Examples ==="
echo ""

for file in "$ROOT_DIR"/examples/*.lux; do
    check_file "$file"
done

echo ""
echo "=== Linting Lux Projects ==="
echo ""

for file in "$ROOT_DIR"/projects/*/main.lux; do
    check_file "$file"
done

echo ""
echo "=== Summary ==="
echo "Passed: $PASSED"
echo "Failed: $FAILED"

if [ $FAILED -gt 0 ]; then
    exit 1
fi

echo ""
echo "All files pass parse and type checking!"
