#!/usr/bin/env bash
#
# Pre-commit validation orchestrator for hyper-element
#
# Runs all pre-commit checks in sequence.
# Exit codes: 0 = pass, 1 = fail

set -e

# Path resolution (works from .git/hooks/ or .hooks/)
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"

if [[ "$SCRIPT_DIR" == *".git/hooks"* ]]; then
    CHECKS_DIR="$SCRIPT_DIR/pre-commit.d"
    PROJECT_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
else
    CHECKS_DIR="$SCRIPT_DIR/pre-commit.d"
    PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
fi

cd "$PROJECT_ROOT"

ERROR=0

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

print_header() {
    echo ""
    echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${YELLOW}  $1${NC}"
    echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
}

run_check() {
    local script="$1"
    local name="$2"

    if [ ! -f "$script" ]; then
        echo -e "${RED}  ✗ Check script not found: $script${NC}"
        ERROR=1
        return
    fi

    echo ""
    echo -e "  Running: $name"

    if [ -x "$script" ]; then
        if "$script"; then
            echo -e "${GREEN}  ✓ $name passed${NC}"
        else
            echo -e "${RED}  ✗ $name failed${NC}"
            ERROR=1
        fi
    else
        if bash "$script"; then
            echo -e "${GREEN}  ✓ $name passed${NC}"
        else
            echo -e "${RED}  ✗ $name failed${NC}"
            ERROR=1
        fi
    fi
}

print_header "Pre-commit Checks"

# Run checks
run_check "$CHECKS_DIR/check-no-c8-ignore.sh" "No c8 ignore"
run_check "$CHECKS_DIR/check-lint.sh" "ESLint"
run_check "$CHECKS_DIR/check-format.sh" "Prettier"
run_check "$CHECKS_DIR/check-build.sh" "Build"
run_check "$CHECKS_DIR/check-coverage.sh" "Tests + Coverage"
run_check "$CHECKS_DIR/check-line-count.sh" "Line Count"
run_check "$CHECKS_DIR/check-docs.sh" "Documentation"
run_check "$CHECKS_DIR/check-jsdoc.sh" "JSDoc"

echo ""
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"

if [ $ERROR -eq 1 ]; then
    echo -e "${RED}  ✗ Commit blocked: One or more checks failed${NC}"
    echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo ""
    exit 1
fi

echo -e "${GREEN}  ✓ All pre-commit checks passed${NC}"
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""
exit 0
