#!/usr/bin/env bash
set -euo pipefail

# Format staged Go files.
STAGED_GO=$(git diff --cached --name-only --diff-filter=ACM | grep '\.go$' || true)
if [ -n "$STAGED_GO" ]; then
  echo "$STAGED_GO" | while IFS= read -r f; do
    gofmt -w "$f"
    git add "$f"
  done
fi

# Lint and format staged web source files. Paths are repo-root relative; we
# strip the leading "web/" so tooling runs inside the web workspace.
cd web

STAGED_WEB_SRC=$(git diff --cached --name-only --diff-filter=ACM | grep -E '^web/src/.*\.(ts|tsx|vue|js|jsx|mjs)$' || true)
if [ -n "$STAGED_WEB_SRC" ]; then
  echo "$STAGED_WEB_SRC" | sed 's|^web/||' | while IFS= read -r f; do
    pnpm exec eslint --fix "$f"
    pnpm exec prettier --write "$f"
    git add "../web/$f"
  done
fi

STAGED_WEB_FMT=$(git diff --cached --name-only --diff-filter=ACM | grep -E '^web/.*\.(css|scss|json|md|yaml|yml)$' || true)
if [ -n "$STAGED_WEB_FMT" ]; then
  echo "$STAGED_WEB_FMT" | sed 's|^web/||' | while IFS= read -r f; do
    pnpm exec prettier --write "$f"
    git add "../web/$f"
  done
fi
