#!/bin/sh
# Pre-commit checks for marktvogt monorepo.
# Replaces .pre-commit-config.yaml (Python pre-commit framework).
# Install via: pnpm install (at repo root). Husky 9 reads this file directly.

set -e

red() { printf '\033[31m%s\033[0m\n' "$*" >&2; }

# 1. Block direct commits to main.
branch=$(git symbolic-ref --short HEAD 2>/dev/null || echo "")
if [ "$branch" = "main" ]; then
  red "ERROR: direct commits to main are blocked. Create a feature branch."
  exit 1
fi

# 2. Detect whitespace errors and merge-conflict markers in staged hunks.
#    Replaces pre-commit-hooks: trailing-whitespace, check-merge-conflict.
if ! git diff --cached --check; then
  red "ERROR: whitespace errors or merge-conflict markers in staged changes."
  exit 1
fi

# 3. Reject staged files larger than 500 KB (excluding crawler test fixtures).
#    Replaces pre-commit-hooks: check-added-large-files.
big=$(git diff --cached --name-only --diff-filter=ACMR -z |
  while IFS= read -r -d '' f; do
    case "$f" in
      backend/internal/domain/discovery/crawler/testdata/*) continue ;;
    esac
    [ -f "$f" ] || continue
    size=$(wc -c <"$f" 2>/dev/null || echo 0)
    if [ "$size" -gt 524288 ]; then
      printf '%s (%s bytes)\n' "$f" "$size"
    fi
  done)
if [ -n "$big" ]; then
  red "ERROR: large files staged (>500 KB):"
  printf '%s\n' "$big" >&2
  exit 1
fi

# Helper: list staged files matching a pattern.
staged_match() {
  git diff --cached --name-only --diff-filter=ACMR | grep -E "$1" || true
}

# 4. Backend Go checks — only when backend/*.go is staged.
if [ -n "$(staged_match '^backend/.*\.go$')" ]; then
  echo "→ backend: gofmt"
  unformatted=$(cd backend && gofmt -l .)
  if [ -n "$unformatted" ]; then
    red "ERROR: gofmt would change these files:"
    printf '%s\n' "$unformatted" >&2
    exit 1
  fi

  echo "→ backend: go vet"
  ( cd backend && go vet ./... )

  echo "→ backend: golangci-lint"
  ( cd backend && golangci-lint run --config .golangci.yml ./... )
fi

# 5. go.mod / go.sum tidy — only when those files are staged.
if [ -n "$(staged_match '^backend/go\.(mod|sum)$')" ]; then
  echo "→ backend: go mod tidy (diff check)"
  ( cd backend && go mod tidy -diff ) || {
    red "ERROR: go mod tidy would change go.mod/go.sum. Run \`cd backend && go mod tidy\` and stage the result."
    exit 1
  }
fi

# 6. Web checks — only when web/ files are staged.
if [ -n "$(staged_match '^web/')" ]; then
  echo "→ web: prettier --check"
  ( cd web && pnpm run format:check )

  echo "→ web: eslint"
  ( cd web && pnpm run lint )

  echo "→ web: svelte-check"
  ( cd web && pnpm run check -- --threshold error )
fi
