#!/usr/bin/env bash
# godot-ui task runner
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

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

cmd_verify() {
    local failed=0

    echo "=== Lint ==="
    if gdlint **/*.gd 2>&1; then
        echo -e "${GREEN}PASS${NC}"
    else
        echo -e "${RED}FAIL${NC}"
        failed=1
    fi

    echo ""
    echo "=== Format Check ==="
    if gdformat --check **/*.gd 2>&1; then
        echo -e "${GREEN}PASS${NC}"
    else
        echo -e "${RED}FAIL${NC} (run: ./run format)"
        failed=1
    fi

    echo ""
    if [[ $failed -eq 0 ]]; then
        echo -e "${GREEN}All checks passed.${NC}"
    else
        echo -e "${RED}Verification failed.${NC}"
        exit 1
    fi
}

cmd_format() {
    echo "Formatting..."
    gdformat **/*.gd
    echo -e "${GREEN}Done.${NC}"
}

cmd_lint() {
    gdlint **/*.gd
}

cmd_test() {
    local godot_bin="${GODOT_BIN:-godot}"
    echo "=== Running Tests ==="
    cd tests
    "$godot_bin" --headless --script res://tests/test_runner.gd 2>&1
    local exit_code=$?
    cd ..
    if [[ $exit_code -eq 0 ]]; then
        echo -e "${GREEN}All tests passed.${NC}"
    else
        echo -e "${RED}Tests failed.${NC}"
        exit $exit_code
    fi
}

cmd_help() {
    echo "godot-ui task runner"
    echo ""
    echo "Usage: ./run <command>"
    echo ""
    echo "Commands:"
    echo "  verify    Lint + format check"
    echo "  format    Auto-format all .gd files"
    echo "  lint      Lint only"
    echo "  test      Run unit tests (needs Godot)"
    echo "  help      Show this help"
}

case "${1:-verify}" in
    verify)  cmd_verify ;;
    format)  cmd_format ;;
    lint)    cmd_lint ;;
    test)    cmd_test ;;
    help)    cmd_help ;;
    *)
        echo -e "${RED}Unknown command: $1${NC}"
        cmd_help
        exit 1
        ;;
esac
