#!/bin/sh
set -e

# Railway sets PORT (usually 8080). Export before anything starts.
export PORT=${PORT:-8080}
export SPENDOS_INTERNAL_URL="http://localhost:${PORT}"

echo "[SpendOS] Starting on port $PORT..."

# Symlink memory + jobs to persistent volume so they survive redeploys
mkdir -p /data/memory
ln -sfn /data/memory /app/memory

# Persist agent-created jobs on volume
mkdir -p /data/jobs
# Copy seed jobs to volume (don't overwrite agent-created ones)
cp -n /app/jobs/*.json /data/jobs/ 2>/dev/null || true
# Symlink so runtime reads/writes to the volume
rm -rf /app/jobs
ln -sfn /data/jobs /app/jobs

# 1. Start SpendOS Express server
npx tsx src/server.ts &
SPENDOS_PID=$!
sleep 3

echo "[SpendOS] Express server started on :${PORT:-3030} (PID $SPENDOS_PID)"

# 2. Configure OpenClaw (only on first boot — check for marker file)
FIRST_BOOT_MARKER="$OPENCLAW_STATE_DIR/.spendos-configured"
if [ ! -f "$FIRST_BOOT_MARKER" ]; then
  echo "[SpendOS] First boot — configuring OpenClaw..."

# Set Venice model via SpendOS proxy
openclaw config set agents.defaults.model.primary "spendos/kimi-k2-5" 2>/dev/null || true
openclaw config set models.providers.spendos '{"baseUrl":"http://localhost:3030/v1","apiKey":"spendos","api":"openai-completions","models":[{"id":"kimi-k2-5","name":"kimi-k2-5","contextWindow":256000}]}' 2>/dev/null || true
openclaw config set agents.defaults.models '{"spendos/kimi-k2-5":{"alias":"Venice via SpendOS"}}' 2>/dev/null || true
openclaw config set gateway.mode local 2>/dev/null || true
openclaw config set gateway.http.endpoints.chatCompletions.enabled true 2>/dev/null || true

# Set SpendOS MCP server (pre-compiled JS — no tsx needed)
openclaw mcp set spendos "{\"command\":\"node\",\"args\":[\"/app/dist/mcp-server.mjs\"],\"env\":{\"SPENDOS_URL\":\"http://localhost:${PORT:-3030}\"}}" 2>/dev/null || true

# Set MoonPay MCP (safe tools only)
openclaw mcp set moonpay '{"command":"npx","args":["@moonpay/cli","mcp"]}' 2>/dev/null || true

# Set Zerion MCP
openclaw mcp set zerion '{"url":"https://developers.zerion.io/mcp","transport":"streamable-http"}' 2>/dev/null || true

# Install SpendOS skill + plugin into OpenClaw
# Install skill
mkdir -p $OPENCLAW_STATE_DIR/skills/spendos
cp /app/skills/spendos/skill.md $OPENCLAW_STATE_DIR/skills/spendos/ 2>/dev/null || true

# Install plugin
mkdir -p $OPENCLAW_STATE_DIR/plugins
cp -r /app/plugins/spendos-events $OPENCLAW_STATE_DIR/plugins/ 2>/dev/null || true
cd $OPENCLAW_STATE_DIR/plugins/spendos-events && npm install --production 2>/dev/null || true
cd /app

# Register plugin with OpenClaw
openclaw config set plugins.spendos-events "{\"path\":\"$OPENCLAW_STATE_DIR/plugins/spendos-events\"}" 2>/dev/null || true

# Set workspace to /app so SOUL.md and AGENTS.md are loaded
openclaw config set agents.defaults.workspace /app 2>/dev/null || true

  # Security: block agent from reading secrets
  openclaw config set tools.exec.env.denylist '["OWS_PASSPHRASE","OWS_IMPORT_MNEMONIC","DEPLOYER_PRIVATE_KEY","SPENDOS_ADMIN_TOKEN","OPENCLAW_GATEWAY_TOKEN_OVERRIDE","TWITTER_USERNAME","TWITTER_PASSWORD"]' 2>/dev/null || true

  # Enable browser tool (Chromium installed in Docker image)
  openclaw config set tools.browser.enabled true 2>/dev/null || true
  openclaw config set tools.browser.executable "$CHROME_BIN" 2>/dev/null || true

  # Restore Twitter cookies from persistent volume if they exist
  if [ -f "/data/twitter-cookies.json" ]; then
    openclaw config set tools.browser.cookies "/data/twitter-cookies.json" 2>/dev/null || true
    echo "[SpendOS] Twitter cookies restored from volume"
  fi

  # Disable Slack channel (not needed, causes MODULE_NOT_FOUND errors)
  openclaw config set channels.slack.enabled false 2>/dev/null || true

  touch "$FIRST_BOOT_MARKER"
  echo "[SpendOS] First boot configuration complete"
else
  echo "[SpendOS] OpenClaw already configured (restarting with existing sessions/memory)"
fi

# ALWAYS update these on every boot (not just first boot)
if [ -n "$OPENCLAW_GATEWAY_TOKEN_OVERRIDE" ]; then
  openclaw config set gateway.auth.token "$OPENCLAW_GATEWAY_TOKEN_OVERRIDE" 2>/dev/null || true
fi
# Re-register SpendOS MCP server (compiled JS, no tsx dependency)
openclaw mcp set spendos "{\"command\":\"node\",\"args\":[\"/app/dist/mcp-server.mjs\"],\"env\":{\"SPENDOS_URL\":\"http://localhost:${PORT:-3030}\"}}" 2>/dev/null || true

# 3. Set up cron jobs (if not already set)
# Get OpenClaw gateway token for internal API calls
# openclaw config get redacts the token, so read directly from the JSON config
export OPENCLAW_GATEWAY_TOKEN=$(node -e "try{const c=JSON.parse(require('fs').readFileSync('$OPENCLAW_STATE_DIR/openclaw.json','utf8'));process.stdout.write(c.gateway?.auth?.token||'')}catch{}" 2>/dev/null || echo "")
export OPENCLAW_INTERNAL_URL="http://localhost:18789"

# OpenClaw gateway on INTERNAL port only — NOT exposed to internet
openclaw gateway --port 18789 &
GATEWAY_PID=$!
sleep 5

echo "[SpendOS] OpenClaw gateway started on :18789 INTERNAL (PID $GATEWAY_PID)"

# Add cron jobs only on first boot
# COST AWARENESS: each cron invocation costs ~$0.05 in Venice inference.
# Only invoke the agent when there's revenue to justify it.
# The venice-topup cron is removed — auto top-up is now built into the proxy.
# Reset crons on every boot to pick up config changes
openclaw cron remove --name "revenue-scanner" 2>/dev/null || true
openclaw cron remove --name "venice-topup" 2>/dev/null || true
if true; then
openclaw cron add \
  --name "revenue-scanner" \
  --every "2h" \
  --agent main \
  --session isolated \
  --timeout-seconds 90 \
  --light-context \
  --message "You are SpendOS. COST RULE: This cron costs ~\$0.05 per run. Only take actions that generate more than \$0.05 in expected value.

Quick check: curl -s http://localhost:3030/api/pnl

If earned > 0 and margin is improving, propose ONE yield delegation.
If no revenue, create ONE new job (write JSON to /app/jobs/ then curl -X POST http://localhost:3030/api/jobs/reload).
If you already created jobs recently, just report status — don't burn credits on busywork.
Keep responses SHORT. Every token costs money." \
  --description "Cost-aware revenue scanner (2h)" \
  2>/dev/null || echo "[SpendOS] Cron already exists"

  touch "$FIRST_BOOT_MARKER.crons"
  echo "[SpendOS] Cron jobs configured"
else
  echo "[SpendOS] Cron jobs already exist"
fi
# 4. Start ACP seller runtime (agent-to-agent commerce marketplace)
# Decode ACP config from base64 env var (injected by setup.sh --deploy)
if [ -n "$ACP_CONFIG_B64" ] && [ -d "/app/acp-seller" ]; then
  echo "$ACP_CONFIG_B64" | base64 -d > /app/acp-seller/config.json
  LITE_AGENT_API_KEY=$(node -e "try{const c=JSON.parse(require('fs').readFileSync('/app/acp-seller/config.json'));process.stdout.write(c.LITE_AGENT_API_KEY||'')}catch{}" 2>/dev/null)
  export LITE_AGENT_API_KEY
  echo "[SpendOS] ACP config decoded from ACP_CONFIG_B64"
fi

if [ -n "$LITE_AGENT_API_KEY" ] && [ -d "/app/acp-seller" ]; then
  echo "[SpendOS] Starting ACP seller runtime..."
  cd /app/acp-seller
  SPENDOS_URL="http://localhost:${PORT:-8080}" GUARDIAN_INTERNAL_API_TOKEN="${GUARDIAN_INTERNAL_API_TOKEN:-skip}" \
    npx tsx bin/acp.ts serve start 2>&1 || echo "[SpendOS] ACP seller failed to start"
  cd /app
  echo "[SpendOS] ACP seller runtime started (accepting jobs from other agents)"
else
  echo "[SpendOS] ACP seller skipped (set LITE_AGENT_API_KEY to enable)"
fi

echo "[SpendOS] System ready:"
echo "  Dashboard (PUBLIC):  http://localhost:${PORT:-8080}"
echo "  OpenClaw (INTERNAL): http://localhost:18789 (not exposed to internet)"
if [ -n "$LITE_AGENT_API_KEY" ]; then
  echo "  ACP Seller:          connected to acpx.virtuals.io (3 offerings)"
fi

# Wait for either process to exit
wait $SPENDOS_PID $GATEWAY_PID
