#!/usr/bin/env bash
# PostToolUse(Write|Edit): format the file that was just written.
# Dispatches by extension; silently skips any formatter that isn't installed.
set -u

f=$(jq -r '.tool_response.filePath // .tool_input.file_path // empty' 2>/dev/null)
[ -n "${f:-}" ] || exit 0
[ -f "$f" ] || exit 0

has() { command -v "$1" >/dev/null 2>&1; }

case "$f" in
  *.py)
    if   has ruff;  then ruff format -- "$f"; ruff check --fix-only -- "$f"
    elif has black; then black -q -- "$f"
    fi ;;
  *.c|*.cc|*.cpp|*.cxx|*.h|*.hpp|*.m|*.mm)
    has clang-format && clang-format -i -- "$f" ;;
  *.rs)
    has rustfmt && rustfmt --edition 2021 -- "$f" ;;
  *.js|*.jsx|*.ts|*.tsx|*.json|*.css|*.scss|*.html|*.md|*.yaml|*.yml)
    has prettier && prettier --write --ignore-unknown -- "$f" ;;
  *.sh|*.bash)
    has shfmt && shfmt -w -- "$f" ;;
  *.go)
    has gofmt && gofmt -w -- "$f" ;;
esac
exit 0
