#!/bin/sh

# Resolve project root (where .git lives)
ROOT="$(git rev-parse --show-toplevel)"

# --- Beads flush (prevent race with daemon auto-flush) ---
if command -v bd >/dev/null 2>&1; then
  BEADS_DIR=""
  if git rev-parse --git-dir >/dev/null 2>&1; then
    if [ "$(git rev-parse --git-dir)" != "$(git rev-parse --git-common-dir)" ]; then
      MAIN_REPO_ROOT="$(dirname "$(git rev-parse --git-common-dir)")"
      [ -d "$MAIN_REPO_ROOT/.beads" ] && BEADS_DIR="$MAIN_REPO_ROOT/.beads"
    else
      [ -d "$ROOT/.beads" ] && BEADS_DIR="$ROOT/.beads"
    fi
  fi

  if [ -n "$BEADS_DIR" ]; then
    if ! bd sync --flush-only >/dev/null 2>&1; then
      echo "Error: Failed to flush bd changes to JSONL" >&2
      exit 1
    fi
    if [ -f "$BEADS_DIR/issues.jsonl" ]; then
      if [ "$(git rev-parse --git-dir)" = "$(git rev-parse --git-common-dir)" ]; then
        git add "$BEADS_DIR/issues.jsonl" 2>/dev/null || true
      fi
    fi
  fi
fi

# --- Linters ---
echo "Running ruff..."
ruff check "$ROOT" || exit 1

echo "Running biome..."
(cd "$ROOT/worca-ui" && npx biome check) || exit 1

# --- UI build check ---
echo "Building worca-ui..."
(cd "$ROOT/worca-ui" && npm run build) || exit 1
