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

echo "============================================"
echo "   Dino API Server - Setup & Start"
echo "============================================"
echo ""

# ── 1. Check Node.js ──────────────────────────────────────────────────
echo "[1/4] Checking Node.js..."
if ! command -v node &>/dev/null; then
    echo "ERROR: Node.js is not installed."
    echo "Please install Node.js from https://nodejs.org/ and re-run this script."
    exit 1
fi
echo "       Found Node.js $(node -v)"

# ── 2. Install pi (if missing) ────────────────────────────────────────
echo "[2/4] Checking pi CLI..."
if command -v pi &>/dev/null; then
    echo "       Found pi $(pi --version 2>&1 || echo '(unknown version)')"
else
    echo "       Installing pi..."
    npm install -g @earendil-works/pi-coding-agent@0.84.4
    echo "       pi installed successfully."
fi

# ── 3. Install Dino via pi (if missing) ───────────────────────────────
echo "[3/4] Checking Dino package..."
DINO_DIR="${HOME}/.pi/agent/npm/node_modules/@assertrx/dino"
if [ ! -d "${DINO_DIR}" ]; then
    echo "       Installing @assertrx/dino via pi..."
    pi install "npm:@assertrx/dino" --approve
    echo "       Dino package installed."
else
    echo "       Dino already installed at ${DINO_DIR}"
fi

# pi-coding-agent@0.85.0 imports @earendil-works/pi-server at runtime
# without declaring it as a dependency (upstream packaging bug), which
# breaks the API server with ERR_MODULE_NOT_FOUND. 0.84.4 is the last
# version that works out of the box, so force it in pi's package dir
# regardless of what dino's "*" dependency resolved to.
PI_NPM_DIR="${HOME}/.pi/agent/npm"
PINNED_PI="0.84.4"
export PI_NPM_DIR PINNED_PI
if ! node -e "const fs=require('fs');let v='';try{v=JSON.parse(fs.readFileSync(process.env.PI_NPM_DIR+'/node_modules/@earendil-works/pi-coding-agent/package.json','utf8')).version}catch(e){}process.exit(v===process.env.PINNED_PI?0:1)"; then
    echo "       Pinning @earendil-works/pi-coding-agent to ${PINNED_PI}..."
    (cd "${PI_NPM_DIR}" && npm install "@earendil-works/pi-coding-agent@${PINNED_PI}" --save-exact --no-fund --no-audit --loglevel=error)
    echo "       Pinned to ${PINNED_PI}."
else
    echo "       pi-coding-agent ${PINNED_PI} (known-good) installed."
fi

if ! (cd "${PI_NPM_DIR}" && node --input-type=module -e "await import('@earendil-works/pi-coding-agent')"); then
    echo "ERROR: pi-coding-agent failed to import."
    exit 1
fi
echo "       pi-coding-agent import check OK."

# ── 4. Start server ───────────────────────────────────────────────────
echo "[4/4] Starting Dino API server..."
echo ""

PORT="${PORT:-4003}"
HOST="${HOST:-0.0.0.0}"

echo "       Port: ${PORT}"
echo "       Host: ${HOST}"

if [ -n "${ANTHROPIC_API_KEY:-}" ]; then
    echo "       API key: loaded from ANTHROPIC_API_KEY"
else
    echo "       WARNING: No ANTHROPIC_API_KEY set. Set it or pass apiKey in request body."
fi

echo ""
echo "       Endpoints:"
echo "         GET  http://${HOST}:${PORT}/api/health"
echo "         GET  http://${HOST}:${PORT}/api/prompts"
echo "         POST http://${HOST}:${PORT}/api/prompts/:name"
echo ""
echo "============================================"
echo ""

exec node "${DINO_DIR}/scripts/api-server.mjs"