#!/usr/bin/env bash
set -euo pipefail
cd /mnt/rpi/repos/ballbox
LOG=/mnt/rpi/agent-logs/agent-bg-20260428.log
exec >> "$LOG" 2>&1

log() { printf '\n[%s] %s\n' "$(date -Is)" "$*"; }
run() { log "+ $*"; "$@"; }

log "orchestrator start"

# ARCH-3
if git show-ref --verify --quiet refs/heads/arch-3-test-taxonomy-split; then
  run git checkout arch-3-test-taxonomy-split
  log "ARCH-3 assumption: moved backend/helper tests belong in unit; keep route/schema/browser coverage in contracts/e2e"
  run pnpm test:unit || true
  run pnpm test:contracts || true
  run pnpm typecheck || true
  run pnpm lint || true
  if ! git diff --quiet; then
    run git add tests vitest.config.ts package.json PLAN.md docs || true
    run git commit -m "Split backend and helper tests into unit taxonomy" || true
    run git push -u origin arch-3-test-taxonomy-split || true
    run gh pr create --base main --head arch-3-test-taxonomy-split --title "ARCH-3 split backend and helper tests into unit taxonomy" --body "## Summary
- move isolated backend/helper tests from contracts to unit taxonomy
- keep route shape coverage in contracts and browser flows in e2e
- update docs and plan to reflect the taxonomy boundary

## Testing
- pnpm test:unit
- pnpm test:contracts
- pnpm typecheck
- pnpm lint" || true
  fi
fi

# PERF-1 prep
if git fetch origin && git checkout main && git pull --ff-only origin main && git checkout -b perf-1-ttfb-pass; then
  log "PERF-1 assumption: measure local production-like TTFB with existing app, optimize only obvious repeated SSR costs"
  run pnpm build || true
  (nohup pnpm start --port 3031 >/tmp/ballbox-perf-3031.log 2>&1 &) || true
  sleep 8
  run bash -lc 'for path in /admin /classes /classes-by-date; do echo "PATH:$path"; curl -s -o /dev/null -w "time_starttransfer=%{time_starttransfer} time_total=%{time_total} code=%{http_code}\n" http://127.0.0.1:3031$path; done' || true
  log "PERF-1 note: awaiting targeted code changes after measurement review"
fi

# PAY-3 prep
if git fetch origin && git checkout main && git pull --ff-only origin main && git checkout -b pay-3-tcn-adapter; then
  log "PAY-3 assumption: implement contract-first stub/minimal adapter over current MercadoPago order route, document unresolved dispense handshake explicitly"
  log "PAY-3 note: not auto-editing payments architecture blindly; resume from docs + schema review"
fi

log "orchestrator end"
