#!/usr/bin/env bash
# bin/compile-check — run ghcid standalone for fast compilation feedback.
#
# Does NOT start postgres or tailwind — just GHC.
# Relies on .ghci (sets -j1, loads IHP config).
#
# Usage:
#   bin/compile-check            # interactive: errors shown in terminal + log
#   bin/compile-check --bg       # log only (for Claude monitoring loop)
#
# Pre-requisite: run inside `devenv shell` (IHP_LIB must be set).
# Or: `devenv shell -- bin/compile-check`
#
# Log file: /tmp/ihub-compile-errors.txt (override with IHUB_COMPILE_LOG)

set -euo pipefail

LOGFILE="${IHUB_COMPILE_LOG:-/tmp/ihub-compile-errors.txt}"
MODE="${1:-}"

# Ensure IHP_LIB is available
if [[ -z "${IHP_LIB:-}" ]]; then
    echo "ERROR: IHP_LIB is not set. Run inside devenv shell:" >&2
    echo "  devenv shell -- bin/compile-check" >&2
    exit 1
fi

: > "$LOGFILE"
echo "[compile-check] Log: $LOGFILE"
echo "[compile-check] Mode: ${MODE:-interactive}"

if [[ "$MODE" == "--bg" ]]; then
    # Background: write to log only, no colour/title
    exec ghcid \
        --no-title \
        --outputfile "$LOGFILE" \
        --command "ghci"
else
    # Interactive: show errors in terminal AND write to log
    exec ghcid \
        --no-title \
        --outputfile "$LOGFILE" \
        --command "ghci"
fi
