#!/usr/bin/env bash
set -Eeuo pipefail
REPO="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd -P)"
PROFILE_NAME="${CHATGPT_COMPUTER_MCP_PROFILE:-chatgpt-computer-mcp}"
SERVICE_NAME="chatgpt-computer-mcp-tunnel.service"
API_FILE="$REPO/.secrets/runtime-api-key"

printf 'Service: '
if systemctl --user is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
  echo ACTIVE
else
  echo NOT_ACTIVE
fi
systemctl --user status "$SERVICE_NAME" --no-pager --lines=12 2>/dev/null || true

if command -v tunnel-client >/dev/null 2>&1 && [[ -r "$API_FILE" ]]; then
  export CONTROL_PLANE_API_KEY="$(head -n1 "$API_FILE" | tr -d '\r\n')"
  export CHATGPT_COMPUTER_MCP_CONFIG="$REPO/config.local.json"
  export HEALTH_LISTEN_ADDR="127.0.0.1:0"
  printf '\nTunnel doctor (%s):\n' "$PROFILE_NAME"
  tunnel-client doctor --profile "$PROFILE_NAME" --explain || true
else
  printf '\nTunnel doctor skipped: tunnel-client or local runtime key is unavailable.\n'
fi
