#!/bin/bash
# ============================================================
# ClickNext AI Security — Claude Code monitoring setup (Mac/Linux)
# Install command (runs in your CURRENT shell via eval):
#   eval "$(curl -s https://caw.clicknext.com/setup-otlp.sh)" && claude
# IMPORTANT: because it is eval'd into the current shell, this script must
# NEVER call `exit` (that would close the user's terminal) or `set -e`.
# ============================================================

echo "Starting ClickNext AI monitoring setup..."

# 1) Node.js (needed for npm). Install via Homebrew if available; otherwise just warn.
if ! command -v node >/dev/null 2>&1; then
  if command -v brew >/dev/null 2>&1; then
    echo "Node.js not found — installing via Homebrew..."
    brew install node
  else
    echo "Node.js not found. Please install it first: https://nodejs.org/  (then re-run this command)"
  fi
fi

# 2) Claude Code (official Anthropic CLI)
if command -v npm >/dev/null 2>&1; then
  echo "Installing Claude Code (@anthropic-ai/claude-code)..."
  npm install -g @anthropic-ai/claude-code --quiet
else
  echo "Skipping Claude Code install — npm not available yet."
fi

# 3) Persist telemetry config for THIS user, in whatever shells they use.
#    Written literally (single-quoted heredoc) so ${USER}/$(hostname) resolve at
#    shell start on the employee's own machine. Idempotent: a marker line guards
#    against duplicate blocks when the one-liner is run more than once.
for _cnx_rc in "$HOME/.zshrc" "$HOME/.bashrc"; do
  [ -e "$_cnx_rc" ] || touch "$_cnx_rc"
  if ! grep -q "ClickNext AI Monitoring" "$_cnx_rc" 2>/dev/null; then
    cat >> "$_cnx_rc" <<'EOT'

# === ClickNext AI Monitoring (managed — do not edit) ===
export CLAUDE_CODE_ENABLE_TELEMETRY=1
export CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1
export OTEL_EXPORTER_OTLP_ENDPOINT=https://caw.clicknext.com
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_LOGS_EXPORTER=otlp
export OTEL_METRICS_EXPORTER=otlp
export OTEL_TRACES_EXPORTER=otlp
export OTEL_SERVICE_NAME=claude-code-employee
export OTEL_RESOURCE_ATTRIBUTES="user.email=${USER}@clicknext.com,device.id=$(hostname)"
# === end ClickNext ===
EOT
    echo "Added ClickNext monitoring config to $_cnx_rc"
  fi
done

# 4) Also apply to the CURRENT shell, so the `claude` you run right now is monitored.
export CLAUDE_CODE_ENABLE_TELEMETRY=1
export CLAUDE_CODE_ENHANCED_TELEMETRY_BETA=1
export OTEL_EXPORTER_OTLP_ENDPOINT=https://caw.clicknext.com
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_LOGS_EXPORTER=otlp
export OTEL_METRICS_EXPORTER=otlp
export OTEL_TRACES_EXPORTER=otlp
export OTEL_SERVICE_NAME=claude-code-employee
export OTEL_RESOURCE_ATTRIBUTES="user.email=${USER}@clicknext.com,device.id=$(hostname)"

echo "SETUP COMPLETE. Your Claude Code usage is now monitored by ClickNext Security."
