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

BRIDGE_URL="${BRIDGE_URL:-https://ocb.ai-powered.ch}"
INSTALL_TOKEN="${INSTALL_TOKEN:-}"
BOT_ID="${BOT_ID:-}"
BOT_PASSWORD="${BOT_PASSWORD:-}"
TENANT_ID="${TENANT_ID:-core}"

for cmd in curl jq openssl launchctl; do
  if ! command -v "$cmd" >/dev/null 2>&1; then
    echo "Missing required command: $cmd" >&2
    exit 1
  fi
done

PATH_DEFAULT="/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin"
export PATH="$PATH_DEFAULT"

OPENCLAW_BIN="${OPENCLAW_BIN:-}"
if [ -z "$OPENCLAW_BIN" ]; then
  OPENCLAW_BIN="$(command -v openclaw || true)"
fi
if [ -z "$OPENCLAW_BIN" ]; then
  OPENCLAW_BIN="$(command -v clawdbot || true)"
fi
if [ -z "$OPENCLAW_BIN" ]; then
  echo "Missing OpenClaw CLI (openclaw/clawdbot). Add it to PATH or set OPENCLAW_BIN." >&2
  exit 1
fi

if [ -z "$BOT_ID" ]; then
  host="$(scutil --get ComputerName 2>/dev/null || hostname)"
  BOT_ID="openclaw-$(echo "$host" | tr '[:upper:]' '[:lower:]' | tr -cs 'a-z0-9-' '-')"
fi

BASE_DIR="$HOME/.openclaw-bridge"
ENV_FILE="$BASE_DIR/bridge.env"
WORKER_SH="$BASE_DIR/worker.sh"
O_SEND="$HOME/bin/ocb-send"
PLIST="$HOME/Library/LaunchAgents/ai.openclaw.bridge-worker.plist"

mkdir -p "$BASE_DIR" "$HOME/bin" "$HOME/Library/LaunchAgents"

if [ -f "$ENV_FILE" ]; then
  # shellcheck disable=SC1090
  source "$ENV_FILE" || true
fi

if [ -z "${BOT_PASSWORD:-}" ]; then
  BOT_PASSWORD="$(openssl rand -hex 16)"
fi

cat >"$ENV_FILE" <<EOF
BRIDGE_URL=${BRIDGE_URL}
BOT_ID=${BOT_ID}
BOT_PASSWORD=${BOT_PASSWORD}
TENANT_ID=${TENANT_ID}
OPENCLAW_BIN=${OPENCLAW_BIN}
PATH=${PATH_DEFAULT}
EOF
chmod 600 "$ENV_FILE"

cat >"$WORKER_SH" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
# shellcheck disable=SC1090
source "$HOME/.openclaw-bridge/bridge.env"
export PATH="${PATH}"

while true; do
  curl -sS -N -u "${BOT_ID}:${BOT_PASSWORD}" "${BRIDGE_URL}/v1/stream?channel=inbox:${BOT_ID}" | while IFS= read -r line; do
    case "$line" in
      "data: "*)
        payload="${line#data: }"
        message_id="$(echo "$payload" | jq -r '.message_id // empty')"
        text="$(echo "$payload" | jq -r '.payload.text // .payload.message // "Bridge message received"')"
        if [ -n "${message_id}" ]; then
          if "${OPENCLAW_BIN}" system event --mode now --text "[BRIDGE][${BOT_ID}] ${text}" >/dev/null 2>&1; then
            jq -nc --arg message_id "${message_id}" '{message_id:$message_id}' \
              | curl -sS -u "${BOT_ID}:${BOT_PASSWORD}" -H 'content-type: application/json' -X POST "${BRIDGE_URL}/v1/ack" -d @- >/dev/null 2>&1 || true
          else
            echo "$(date -u +%FT%TZ) WARN failed to dispatch local system event for ${message_id}" >&2
          fi
        fi
      ;;
    esac
  done
  sleep 2
done
EOF
chmod +x "$WORKER_SH"

cat >"$O_SEND" <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
# shellcheck disable=SC1090
source "$HOME/.openclaw-bridge/bridge.env"
TO="${1:-}"
TEXT="${2:-}"
if [ -z "$TO" ] || [ -z "$TEXT" ]; then
  echo "Usage: ocb-send <inbox:bot|topic:name> <text>" >&2
  exit 1
fi
jq -nc \
  --arg tenant_id "${TENANT_ID}" \
  --arg from_bot "${BOT_ID}" \
  --arg to "${TO}" \
  --arg text "${TEXT}" \
  '{tenant_id:$tenant_id,from_bot:$from_bot,to:$to,type:"notification",payload:{text:$text}}' \
  | curl -sS -u "${BOT_ID}:${BOT_PASSWORD}" -H 'content-type: application/json' -X POST "${BRIDGE_URL}/v1/messages" -d @- | jq .
EOF
chmod +x "$O_SEND"

cat >"$PLIST" <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>ai.openclaw.bridge-worker</string>
  <key>ProgramArguments</key>
  <array>
    <string>/bin/bash</string>
    <string>-lc</string>
    <string>${WORKER_SH}</string>
  </array>
  <key>EnvironmentVariables</key>
  <dict>
    <key>PATH</key>
    <string>${PATH_DEFAULT}</string>
  </dict>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>StandardOutPath</key>
  <string>${BASE_DIR}/worker.out.log</string>
  <key>StandardErrorPath</key>
  <string>${BASE_DIR}/worker.err.log</string>
</dict>
</plist>
EOF

launchctl bootout "gui/$(id -u)" "$PLIST" >/dev/null 2>&1 || true
launchctl bootstrap "gui/$(id -u)" "$PLIST"
launchctl enable "gui/$(id -u)/ai.openclaw.bridge-worker"
launchctl kickstart -k "gui/$(id -u)/ai.openclaw.bridge-worker"

if [ -n "$INSTALL_TOKEN" ]; then
  jq -nc \
    --arg install_token "$INSTALL_TOKEN" \
    --arg bot_id "$BOT_ID" \
    --arg password "$BOT_PASSWORD" \
    --arg tenant_id "$TENANT_ID" \
    '{install_token:$install_token,bot_id:$bot_id,password:$password,tenant_id:$tenant_id}' \
    | curl -sS -X POST "${BRIDGE_URL}/v1/register" -H 'content-type: application/json' -d @- | jq .
else
  echo "WARN: INSTALL_TOKEN not set; registration skipped"
fi

echo "Installed macOS bridge worker."
echo "Bot ID: ${BOT_ID}"
echo "LaunchAgent: ai.openclaw.bridge-worker"
echo "Send test: ~/bin/ocb-send inbox:openclaw-sergio 'hello'"
