#!/bin/sh
# pre-commit — typecheck the generated omp port before committing.
#
# Mirrors the CI port job (.gitea/workflows/port-to-omp.yml). The source
# repo's own tsconfig extends the host harness tsconfig and is not
# self-contained, so the reliable typecheck target is the regenerated port:
# it ships a self-contained tsconfig and the pinned @oh-my-pi SDK as a real
# devDependency. Regenerating into a temp dir and running `tsc --noEmit`
# there catches exactly what CI will fail on (e.g. an interface field added
# without updating its object literals).
#
# Enable (per clone):  git config core.hooksPath .githooks
set -euo pipefail

ROOT="$(git rev-parse --show-toplevel)"
cd "$ROOT"

# Fast path: no TypeScript-adjacent change staged -> nothing to typecheck.
if git diff --cached --quiet -- src/ agents/ package.json tsconfig.json port-to-omp.mjs; then
  exit 0
fi

TMP="$(mktemp -d)"
LOG="$(mktemp)"
trap 'rm -rf "$TMP" "$LOG"' EXIT

if ! bun port-to-omp.mjs --out "$TMP" >"$LOG" 2>&1; then
  echo "pre-commit: port regeneration failed (CI would fail too) — output:" >&2
  tail -20 "$LOG" >&2
  exit 1
fi

if ! (cd "$TMP" && bun run typecheck) >"$LOG" 2>&1; then
  echo "pre-commit: port typecheck failed (this is what CI runs) — output:" >&2
  tail -30 "$LOG" >&2
  exit 1
fi
