#!/usr/bin/env bash
# Runs each time the container starts. Waits for the server, then writes
# projects.yml so the indexer picks up the repo via its hot-reload watcher.
#
# Scope is intentionally narrow (packages/shared/src) — the embedding model
# runs on the Codespace CPU and would otherwise take 15+ minutes (with
# occasional batch timeouts on large files) to index the whole repo. The
# narrow scope produces a usable search index in ~2 minutes and is enough
# to demo `paparats search`. Widen via `paparats edit projects` once you
# move to a cloud embedding provider.
set -euo pipefail

SERVER_URL="${PAPARATS_SERVER_URL:-http://localhost:9876}"
PAPARATS_HOME="${HOME}/.paparats"

echo "== Waiting for paparats-mcp at ${SERVER_URL} =="
for i in $(seq 1 60); do
  if curl -fsS "${SERVER_URL}/health" >/dev/null 2>&1; then
    echo "  ready after ${i}s"
    break
  fi
  sleep 1
done

if ! curl -fsS "${SERVER_URL}/health" >/dev/null 2>&1; then
  echo "!! Server did not become healthy in 60s. Check 'docker compose logs paparats'."
  exit 0
fi

mkdir -p "${PAPARATS_HOME}"
cat > "${PAPARATS_HOME}/projects.yml" <<'YML'
# Auto-generated by .devcontainer/post-start.sh for the Codespaces demo.
# Edit freely — the indexer hot-reloads on save.
repos:
  - path: /workspaces/paparats-mcp
    name: paparats-mcp
    group: demo
    language: typescript
    indexing:
      paths:
        - 'packages/shared/src/**'
YML

echo
echo "== Registered paparats-mcp (group=demo, scope=packages/shared/src) =="
echo "Indexer is running on Ollama CPU — first index takes a few minutes."
echo "Watch progress: docker compose -f .devcontainer/docker-compose.yml logs -f indexer"
echo "Then try:        paparats search -g demo 'gitignore filter'"
