#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ENV_FILE="${ENV_FILE:-${ROOT_DIR}/.env.release}"
COMPOSE_FILE="${COMPOSE_FILE:-${ROOT_DIR}/docker-compose.yaml}"
API_PORT="${API_PORT:-8080}"
REGISTRY="${CLAWHUB_REGISTRY:-http://127.0.0.1:${API_PORT}}"

cd "${ROOT_DIR}"

echo "Loading SkillHub Docker images..."
bash scripts/load-images.sh

echo "Starting SkillHub..."
docker compose --env-file "${ENV_FILE}" -f "${COMPOSE_FILE}" up -d

echo "Waiting for backend health at ${REGISTRY}/actuator/health ..."
for _ in $(seq 1 90); do
  if curl -fsS "${REGISTRY}/actuator/health" >/dev/null 2>&1; then
    break
  fi
  sleep 2
done

if ! curl -fsS "${REGISTRY}/actuator/health" >/dev/null 2>&1; then
  echo "SkillHub backend did not become healthy in time." >&2
  docker compose --env-file "${ENV_FILE}" -f "${COMPOSE_FILE}" ps >&2
  exit 1
fi

echo "Publishing bundled seed skills to ${REGISTRY} ..."
export CLAWHUB_REGISTRY="${REGISTRY}"

bash scripts/publish-seed-skills.sh seed-skills/dev-tools dev-tools

if [ -d seed-skills/github ]; then
  while IFS= read -r source_dir; do
    namespace="$(basename "${source_dir}" | tr '_' '-')"
    bash scripts/publish-seed-skills.sh "${source_dir}" "${namespace}"
  done < <(find seed-skills/github -mindepth 1 -maxdepth 1 -type d | sort)
fi

echo "SkillHub is ready."
echo "Web: ${SKILLHUB_PUBLIC_BASE_URL:-http://127.0.0.1:${WEB_PORT:-80}}"
echo "API: ${REGISTRY}"
