#!/usr/bin/env bash

set -euo pipefail

IMAGE="${IMAGE:-blender-ai-mcp:local}"
MCP_HTTP_HOST="${MCP_HTTP_HOST:-0.0.0.0}"
MCP_HTTP_PORT="${MCP_HTTP_PORT:-8000}"
MCP_STREAMABLE_HTTP_PATH="${MCP_STREAMABLE_HTTP_PATH:-/mcp}"
BLENDER_RPC_HOST="${BLENDER_RPC_HOST:-host.docker.internal}"

VISION_OPENROUTER_MODEL="${VISION_OPENROUTER_MODEL:-openai/gpt-5.4-mini}"
VISION_OPENROUTER_SITE_URL="${VISION_OPENROUTER_SITE_URL:-https://example.com}"
VISION_OPENROUTER_SITE_NAME="${VISION_OPENROUTER_SITE_NAME:-blender-ai-mcp-dev}"
VISION_OPENROUTER_REQUIRE_PARAMETERS="${VISION_OPENROUTER_REQUIRE_PARAMETERS:-false}"
VISION_OPENROUTER_ENABLE_RESPONSE_HEALING="${VISION_OPENROUTER_ENABLE_RESPONSE_HEALING:-true}"
VISION_OPENROUTER_PREFER_JSON_OBJECT_FOR_QWEN="${VISION_OPENROUTER_PREFER_JSON_OBJECT_FOR_QWEN:-true}"
VISION_EXTERNAL_CONTRACT_PROFILE="${VISION_EXTERNAL_CONTRACT_PROFILE:-}"
VISION_MAX_IMAGES="${VISION_MAX_IMAGES:-8}"
VISION_MAX_TOKENS="${VISION_MAX_TOKENS:-600}"
VISION_TIMEOUT_SECONDS="${VISION_TIMEOUT_SECONDS:-120}"
MCP_PROMPTS_AS_TOOLS_ENABLED="${MCP_PROMPTS_AS_TOOLS_ENABLED:-false}"

if [[ -z "${OPENROUTER_API_KEY:-}" ]]; then
  echo "OPENROUTER_API_KEY must be set before running this script." >&2
  exit 1
fi

echo "Starting ${IMAGE} in stateful Streamable HTTP mode on http://127.0.0.1:${MCP_HTTP_PORT}${MCP_STREAMABLE_HTTP_PATH}"
echo "Blender RPC host: ${BLENDER_RPC_HOST}"
echo "Prompt bridge tools: ${MCP_PROMPTS_AS_TOOLS_ENABLED}"

exec docker run --rm \
  -p "${MCP_HTTP_PORT}:${MCP_HTTP_PORT}" \
  -v /tmp:/tmp \
  -e BLENDER_AI_TMP_INTERNAL_DIR=/tmp \
  -e BLENDER_AI_TMP_EXTERNAL_DIR=/tmp \
  -e MCP_TRANSPORT_MODE=streamable \
  -e MCP_HTTP_HOST="${MCP_HTTP_HOST}" \
  -e MCP_HTTP_PORT="${MCP_HTTP_PORT}" \
  -e MCP_STREAMABLE_HTTP_PATH="${MCP_STREAMABLE_HTTP_PATH}" \
  -e MCP_PROMPTS_AS_TOOLS_ENABLED="${MCP_PROMPTS_AS_TOOLS_ENABLED}" \
  -e BLENDER_RPC_HOST="${BLENDER_RPC_HOST}" \
  -e ROUTER_ENABLED=true \
  -e MCP_SURFACE_PROFILE=llm-guided \
  -e VISION_ENABLED=true \
  -e VISION_PROVIDER=openai_compatible_external \
  -e VISION_EXTERNAL_PROVIDER=openrouter \
  -e VISION_EXTERNAL_CONTRACT_PROFILE="${VISION_EXTERNAL_CONTRACT_PROFILE}" \
  -e VISION_OPENROUTER_MODEL="${VISION_OPENROUTER_MODEL}" \
  -e VISION_OPENROUTER_API_KEY_ENV=OPENROUTER_API_KEY \
  -e OPENROUTER_API_KEY="${OPENROUTER_API_KEY}" \
  -e VISION_OPENROUTER_SITE_URL="${VISION_OPENROUTER_SITE_URL}" \
  -e VISION_OPENROUTER_SITE_NAME="${VISION_OPENROUTER_SITE_NAME}" \
  -e VISION_OPENROUTER_REQUIRE_PARAMETERS="${VISION_OPENROUTER_REQUIRE_PARAMETERS}" \
  -e VISION_OPENROUTER_ENABLE_RESPONSE_HEALING="${VISION_OPENROUTER_ENABLE_RESPONSE_HEALING}" \
  -e VISION_OPENROUTER_PREFER_JSON_OBJECT_FOR_QWEN="${VISION_OPENROUTER_PREFER_JSON_OBJECT_FOR_QWEN}" \
  -e VISION_ALLOW_ON_GUIDED=true \
  -e VISION_MAX_IMAGES="${VISION_MAX_IMAGES}" \
  -e VISION_MAX_TOKENS="${VISION_MAX_TOKENS}" \
  -e VISION_TIMEOUT_SECONDS="${VISION_TIMEOUT_SECONDS}" \
  -e PYTHONUNBUFFERED=1 \
  "${IMAGE}"
