#!/bin/sh
# OwnCord pre-commit hook — fast, staged-file-aware checks that mirror CI's
# cheapest gates so errors surface in seconds instead of a 15-minute CI run.
#
# Enable once per clone:  npm run hooks:install   (git config core.hooksPath .githooks)
# Bypass in an emergency: git commit --no-verify  or  OWNCORD_SKIP_HOOKS=1
# CI still enforces everything — bypassing only defers the failure.

[ "${OWNCORD_SKIP_HOOKS:-0}" = "1" ] && exit 0

repo_root=$(git rev-parse --show-toplevel) || exit 1
cd "$repo_root" || exit 1

staged=$(git diff --cached --name-only --diff-filter=ACMR)
[ -z "$staged" ] && exit 0

fail() {
    printf '\npre-commit: FAIL: %s\n(bypass with --no-verify; CI will still enforce this)\n' "$1" >&2
    exit 1
}

# ---------- Server (Go) ----------
go_staged=$(printf '%s\n' "$staged" | grep '^Server/.*\.go$' | grep -v '^Server/db/dbgen/')
if [ -n "$go_staged" ]; then
    if command -v go >/dev/null 2>&1; then
        # shellcheck disable=SC2086 — repo paths contain no spaces
        unformatted=$(gofmt -l $go_staged)
        [ -n "$unformatted" ] && fail "gofmt needed (run gofmt -w on): $unformatted"
        (cd Server && go vet ./...) || fail "go vet"
    else
        printf 'pre-commit: WARNING: go not installed; skipping Go checks.\n' >&2
    fi
fi

# sqlc inputs changed -> regenerated db/dbgen must be part of the same commit.
if printf '%s\n' "$staged" | grep -qE '^Server/(db/queries/|migrations/|sqlc\.yaml|sqlc\.version)'; then
    if command -v sqlc >/dev/null 2>&1; then
        (cd Server && make sqlc-verify) \
            || fail "db/dbgen is stale — run 'make sqlc-generate' in Server/ and stage the result"
    else
        printf 'pre-commit: WARNING: sqlc not installed (make sqlc-install); CI will run sqlc-verify.\n' >&2
    fi
fi

# Protocol schema changed -> regenerated Go + TS constants must be in the same commit.
if printf '%s\n' "$staged" | grep -qE '^(docs/protocol-schema\.json|Server/scripts/genprotocol/)'; then
    if command -v go >/dev/null 2>&1; then
        (cd Server && make protocol-verify) \
            || fail "protocol constants are stale — run 'make protocol-generate' in Server/ and stage the result"
    fi
fi

# ---------- Client (TypeScript) ----------
ts_staged=$(printf '%s\n' "$staged" | grep -E '^Client/tauri-client/(src|tests)/.*\.ts$' | grep -v '/generated/')
if [ -n "$ts_staged" ]; then
    if [ ! -d Client/tauri-client/node_modules ]; then
        printf 'pre-commit: WARNING: node_modules missing in Client/tauri-client; skipping client checks (run npm install there).\n' >&2
    else
        rel=$(printf '%s\n' "$ts_staged" | sed 's|^Client/tauri-client/||')
        cd Client/tauri-client || exit 1
        # shellcheck disable=SC2086
        npx oxlint $rel || fail "oxlint"
        # shellcheck disable=SC2086
        npx prettier --check $rel || fail "prettier (run: npm run format)"
        npm run -s typecheck || fail "tsc --noEmit"
        cd "$repo_root" || exit 1
    fi
fi

exit 0
