#!/usr/bin/env bash
# golive-daily.sh — refresh the GOLIVE scoreboard and land it on main.
# Usage: bash scripts/golive-daily.sh [--dry-run]
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
WORKTREE="${GOLIVE_DAILY_WORKTREE:-$HOME/.cache/golive-daily/multideal}"
# The only evidence a probe needs that git does not track: the generated flowmap specs AC-35 counts.
IGNORED_EVIDENCE='apps/web/tests/e2e/flowmap'

if [[ "${1:-}" == "--dry-run" ]]; then
  cd "$ROOT"
  node scripts/golive-probes.mjs
  node scripts/golive-sweep.mjs
  echo "=== golive-daily: dry run — GOLIVE.md updated in place, nothing committed ==="
  exit 0
fi

OWNS_WORKTREE=0
cleanup() {
  if [[ "$OWNS_WORKTREE" -eq 1 ]]; then
    git -C "$ROOT" worktree remove --force "$WORKTREE" 2>/dev/null || true
    git -C "$ROOT" worktree prune
  fi
}
trap cleanup EXIT

# Verdicts land on main, so they are observed on main — never on whatever the developer checkout holds.
cd "$ROOT"
echo "=== golive-daily: preparing a clean origin/main ==="
git fetch origin main
git worktree remove --force "$WORKTREE" 2>/dev/null || true
git worktree prune
git worktree add --detach "$WORKTREE" origin/main
OWNS_WORKTREE=1

# The commit hook runs lint-staged from the workspace; a fresh worktree has no installed packages.
for dir in "" apps/web; do
  target="$ROOT/${dir:+$dir/}node_modules"
  link="$WORKTREE/${dir:+$dir/}node_modules"
  [[ -d "$target" && ! -e "$link" ]] && ln -s "$target" "$link"
done
[[ -d "$ROOT/$IGNORED_EVIDENCE" && ! -e "$WORKTREE/$IGNORED_EVIDENCE" ]] &&
  cp -r "$ROOT/$IGNORED_EVIDENCE" "$WORKTREE/$IGNORED_EVIDENCE"

cd "$WORKTREE"
echo "=== golive-daily: probing ==="
node scripts/golive-probes.mjs
echo "=== golive-daily: sweeping ==="
node scripts/golive-sweep.mjs

if [[ -z "$(git status --porcelain -- GOLIVE.md golive.probes.json golive.judgement.json)" ]]; then
  echo "=== golive-daily: scoreboard unchanged — nothing to land ==="
  exit 0
fi

git add GOLIVE.md golive.probes.json golive.judgement.json
git -c user.name='golive-daily' -c user.email='golive-daily@multideal.local' \
  commit -m "Refresh GOLIVE scoreboard"
bash scripts/land.sh

# Overdeck reads GOLIVE.md from the developer checkout's disk; sync it so the
# dashboard shows the verdicts just landed. Best-effort — skip if the checkout
# is mid-work (not on main, or cannot fast-forward).
if [[ "$(git -C "$ROOT" rev-parse --abbrev-ref HEAD)" == "main" ]]; then
  git -C "$ROOT" pull --ff-only --quiet || true
fi
