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

cd "$(dirname "$0")/../services/mcp"

RUNTIME="${MCP_RUNTIME:-hono}"

pnpm install --frozen-lockfile

# `.env` is the canonical local-dev env (see .env.example) - make sure it
# exists, otherwise OAuth metadata advertises cloud (`oauth.posthog.com`)
# and MCP clients try to auth against production instead of local Django.
if [ ! -f .env ]; then
    cp .env.example .env
    if [ -f .dev.vars ]; then
        echo "NOTE: .dev.vars is no longer read - created .env from .env.example." >&2
        echo "Move any custom values from .dev.vars into .env, then delete .dev.vars." >&2
    fi
fi

# SITE_URL on devboxes points at the public per-workspace subdomain; rewrite
# the three PostHog-pointing keys so MCP's OAuth metadata advertises a host
# browsers can actually reach. Runs every start (not just first creation) so
# .env stays in sync when the workspace subdomain changes.
loopback_re='^https?://(localhost|127\.0\.0\.1)([:/]|$)'
if [ -n "${SITE_URL:-}" ] && ! [[ "${SITE_URL}" =~ $loopback_re ]]; then
    tmp=$(mktemp)
    grep -Ev '^(POSTHOG_API_BASE_URL|POSTHOG_MCP_APPS_ANALYTICS_BASE_URL|POSTHOG_ANALYTICS_HOST)=' .env > "$tmp" || true
    mv "$tmp" .env
    # Leading \n guards against the prior file missing a trailing newline.
    printf '\n%s\n%s\n%s\n' \
        "POSTHOG_API_BASE_URL=${SITE_URL}" \
        "POSTHOG_MCP_APPS_ANALYTICS_BASE_URL=${SITE_URL}" \
        "POSTHOG_ANALYTICS_HOST=${SITE_URL}" \
        >> .env
fi

if [ "$RUNTIME" = "hono" ]; then
    export REDIS_URL="${REDIS_URL:-redis://localhost:6379}"
    export PORT="${PORT:-8787}"
    exec pnpm run dev
else
    # Edge-proxy worker only (wrangler dev) - the MCP protocol itself is
    # served by the Hono runtime. Wrangler reads `.env` when `.dev.vars`
    # is absent.
    exec pnpm run dev:proxy
fi
