#!/usr/bin/env bash
# Pre-commit hook: runs ruff lint/format checks and keeps SKILL.md in sync.
# Install: make hooks  (or: cp scripts/pre-commit .git/hooks/pre-commit && chmod +x .git/hooks/pre-commit)

set -e

# Collect staged .py files
STAGED=$(git diff --cached --name-only --diff-filter=ACM | grep '\.py$' || true)

if [ -n "$STAGED" ]; then
    echo "pre-commit: checking ${STAGED}" | head -5

    # Lint check (ruff check)
    if ! uv run ruff check $STAGED; then
        echo ""
        echo "Lint failed. Run 'make lint-fix' to auto-fix, then re-stage."
        exit 1
    fi

    # Format check (ruff format)
    if ! uv run ruff format --check $STAGED 2>/dev/null; then
        echo ""
        echo "Format check failed. Run 'make format' to fix, then re-stage."
        exit 1
    fi

    # Type check (ty -- BLOCKS the commit on any error; backlog cleared in 0.45.0,
    # see issue #280 PR-3). Warnings (e.g. the downgraded unresolved-import rule)
    # do not block.
    if command -v uv >/dev/null 2>&1; then
        TY_OUTPUT="$(uv run --quiet ty check $STAGED 2>&1 || true)"
        if echo "$TY_OUTPUT" | grep -qiE "^error"; then
            echo ""
            echo "pre-commit: ty type-check found errors (blocking -- fix before committing):"
            echo "$TY_OUTPUT" | tail -20
            echo "Run 'make typecheck' for full output."
            exit 1
        fi
    fi
fi

# Auto-regenerate SKILL.md if CLI commands changed
SKILL_FILE="plugins/kbagent/skills/kbagent/SKILL.md"
if [ -f "scripts/generate_skill.py" ]; then
    uv run python scripts/generate_skill.py > /dev/null 2>&1
    if ! git diff --quiet "$SKILL_FILE" 2>/dev/null; then
        git add "$SKILL_FILE"
        echo "pre-commit: auto-updated $SKILL_FILE"
    fi
fi

# Auto-sync plugin.json version from pyproject.toml
PLUGIN_JSON="plugins/kbagent/.claude-plugin/plugin.json"
if [ -f "scripts/sync_version.py" ]; then
    uv run python scripts/sync_version.py > /dev/null 2>&1
    if ! git diff --quiet "$PLUGIN_JSON" 2>/dev/null; then
        git add "$PLUGIN_JSON"
        echo "pre-commit: auto-synced $PLUGIN_JSON version"
    fi
fi
