#!/bin/bash
set -euo pipefail

readonly BASEDIR="/opt/bytelyst/learning_ai_common_plat"
readonly TOKEN_FILE="${GITEA_NPM_TOKEN_FILE:-$HOME/.gitea_npm_token}"

if [[ -z "${GITEA_NPM_TOKEN:-}" ]]; then
  if [[ -f "$TOKEN_FILE" ]]; then
    export GITEA_NPM_TOKEN
    GITEA_NPM_TOKEN="$(<"$TOKEN_FILE")"
  else
    echo "Need GITEA_NPM_TOKEN (file $TOKEN_FILE or env)."
    exit 1
  fi
fi

source "$BASEDIR/scripts/switch-network.sh" >/dev/null
export NETWORK="${NETWORK:-home}"

cd "$BASEDIR"
corepack pnpm install
corepack pnpm test

echo "Verifying HTTP responses..."
gitea_host="${GITEA_NPM_HOST:-gitea.bytelyst.com}"
if [[ "$gitea_host" == "localhost" || "$gitea_host" == "127.0.0.1" ]]; then
  gitea_host="gitea.bytelyst.com"
fi
gitea_registry_url="https://${gitea_host}/api/packages/learning_ai_user/npm/@bytelyst%2ferrors"

for url in \
  https://api.bytelyst.com/platform/health \
  "$gitea_registry_url" \
  https://ollama.bytelyst.com/api/version \
; do
  if [[ "$url" == "$gitea_registry_url" ]]; then
    if curl -sSf -H "Authorization: token ${GITEA_NPM_TOKEN}" "$url" >/tmp/last-curl.out; then
      echo "$url -> ok"
    else
      echo "$url -> failed, see /tmp/last-curl.out"
    fi
  elif curl -sSfI "$url" >/tmp/last-curl.out; then
    status=$(head -n1 /tmp/last-curl.out)
    echo "$url -> $status"
  else
    echo "$url -> failed, see /tmp/last-curl.out"
  fi
done

echo "Done. pnpm install/test + endpoint verification complete."
