#!/bin/sh

# Claudible Installer for OpenClaw
# Configures OpenClaw Telegram AI bot to use Claudible

set -e

# Configuration (auto-populated by server)
ENDPOINT_URL="https://claudible.io"
API_KEY='YOUR_KEY'
HAIKU_MODEL="claude-haiku-4.5"
OPUS_MODEL="claude-opus-4.6"
SONNET_MODEL="claude-sonnet-4.6"
TELEGRAM_BOT_TOKEN=""
TELEGRAM_USER_ID=""

# Colors
RED=$(printf '\033[0;31m')
GREEN=$(printf '\033[0;32m')
YELLOW=$(printf '\033[1;33m')
BLUE=$(printf '\033[0;34m')
NC=$(printf '\033[0m')

echo "${BLUE}================================${NC}"
echo "${BLUE}  OpenClaw Configuration${NC}"
echo "${BLUE}================================${NC}"
echo ""

# Validate server-injected configuration
if [ "$ENDPOINT_URL" = "__""ENDPOINT_URL__" ] || [ -z "$ENDPOINT_URL" ]; then
    echo "${RED}Error: Endpoint URL not configured${NC}"
    exit 1
fi

if [ "$API_KEY" = "__""API_KEY__" ] || [ -z "$API_KEY" ]; then
    echo "${RED}Error: API key not configured${NC}"
    exit 1
fi

# Mask API key for display
MASKED_KEY=$(echo "$API_KEY" | cut -c 1-10)
echo "Endpoint URL: ${GREEN}$ENDPOINT_URL${NC}"
echo "API Key:      ${GREEN}${MASKED_KEY}...${NC}"
echo ""

# Check jq installed
if ! command -v jq >/dev/null 2>&1; then
    echo ""
    echo "${RED}Error: jq is required but not installed.${NC}"
    echo ""
    echo "Please install jq first:"
    echo "  ${BLUE}macOS:${NC}        brew install jq"
    echo "  ${BLUE}Ubuntu/Debian:${NC} sudo apt-get install -y jq"
    echo "  ${BLUE}Fedora/RHEL:${NC}   sudo dnf install -y jq"
    echo "  ${BLUE}Arch Linux:${NC}    sudo pacman -S jq"
    echo ""
    echo "Then run this installer again."
    exit 1
fi

# Prompt for Telegram Bot Token if not provided
if [ "$TELEGRAM_BOT_TOKEN" = "__""TELEGRAM_BOT_TOKEN__" ] || [ -z "$TELEGRAM_BOT_TOKEN" ]; then
    CAN_PROMPT=0
    if { exec 3</dev/tty; } 2>/dev/null; then
        CAN_PROMPT=1
    fi
    if [ "$CAN_PROMPT" = 0 ]; then
        echo "${RED}Error: No TTY available for interactive input.${NC}"
        echo ""
        echo "Please pass bot token and user ID via URL query parameters:"
        echo "  ${BLUE}curl -fsSL \"$ENDPOINT_URL/openclaw-install.sh?key=YOUR_KEY&bot=BOT_TOKEN&uid=USER_ID\" | sh${NC}"
        exit 1
    fi

    while true; do
        printf "${YELLOW}Enter Telegram Bot Token (from @BotFather): ${NC}"
        read TELEGRAM_BOT_TOKEN <&3
        if [ -z "$TELEGRAM_BOT_TOKEN" ]; then
            echo "${RED}  Bot token cannot be empty.${NC}"
            continue
        fi
        # Validate format: digits:alphanumeric
        if echo "$TELEGRAM_BOT_TOKEN" | grep -qE '^[0-9]+:[A-Za-z0-9_-]+$'; then
            break
        else
            echo "${RED}  Invalid format. Expected: 123456789:ABCDefGhIjK...${NC}"
        fi
    done
fi

# Prompt for Telegram User ID if not provided
if [ "$TELEGRAM_USER_ID" = "__""TELEGRAM_USER_ID__" ] || [ -z "$TELEGRAM_USER_ID" ]; then
    CAN_PROMPT=0
    if { exec 3</dev/tty; } 2>/dev/null; then
        CAN_PROMPT=1
    fi
    if [ "$CAN_PROMPT" = 0 ]; then
        echo "${RED}Error: No TTY available for interactive input.${NC}"
        echo ""
        echo "Please pass user ID via URL query parameters:"
        echo "  ${BLUE}curl -fsSL \"$ENDPOINT_URL/openclaw-install.sh?key=YOUR_KEY&bot=BOT_TOKEN&uid=USER_ID\" | sh${NC}"
        exit 1
    fi

    while true; do
        printf "${YELLOW}Enter Telegram User ID (numeric): ${NC}"
        read TELEGRAM_USER_ID <&3
        if [ -z "$TELEGRAM_USER_ID" ]; then
            echo "${RED}  User ID cannot be empty.${NC}"
            continue
        fi
        # Validate digits only
        if echo "$TELEGRAM_USER_ID" | grep -qE '^[0-9]+$'; then
            break
        else
            echo "${RED}  Invalid format. User ID must be numeric (e.g., 123456789).${NC}"
        fi
    done
fi

echo ""
BOT_LEN=$(printf '%s' "$TELEGRAM_BOT_TOKEN" | wc -c | tr -d ' ')
if [ "$BOT_LEN" -gt 12 ]; then
    MASKED_BOT=$(echo "$TELEGRAM_BOT_TOKEN" | sed 's/\(.\{8\}\).*\(.\{4\}\)$/\1...\2/')
else
    MASKED_BOT=$(printf '%s' "$TELEGRAM_BOT_TOKEN" | cut -c 1-4)
    MASKED_BOT="${MASKED_BOT}..."
fi
echo "Bot Token: ${GREEN}${MASKED_BOT}${NC}"
echo "User ID:   ${GREEN}${TELEGRAM_USER_ID}${NC}"
echo ""

# Define config paths
CONFIG_DIR="$HOME/.openclaw"
CONFIG_FILE="$CONFIG_DIR/config.json"

# Try to read existing gateway token, generate new if not found
GATEWAY_TOKEN=""
if [ -f "$CONFIG_FILE" ]; then
    GATEWAY_TOKEN=$(jq -r '.gateway.auth.token // empty' "$CONFIG_FILE" 2>/dev/null)
fi
if [ -z "$GATEWAY_TOKEN" ]; then
    if command -v openssl >/dev/null 2>&1; then
        GATEWAY_TOKEN=$(openssl rand -hex 16)
    else
        GATEWAY_TOKEN=$(head -c 16 /dev/urandom | od -An -tx1 | tr -d ' \n')
    fi
fi

# Create config directory

mkdir -p "$CONFIG_DIR"

# Backup existing config
if [ -f "$CONFIG_FILE" ]; then
    BACKUP_FILE="${CONFIG_FILE}.backup.$(date +%Y%m%d%H%M%S)"
    cp "$CONFIG_FILE" "$BACKUP_FILE"
    echo "${YELLOW}Backed up existing config: $BACKUP_FILE${NC}"
fi

# Build base URL with /v1
BASE_API_URL="${ENDPOINT_URL}/v1"

# Build config.json via jq
echo "${BLUE}Generating config...${NC}"

jq -n \
    --arg baseUrl "$BASE_API_URL" \
    --arg apiKey "$API_KEY" \
    --arg haiku "$HAIKU_MODEL" \
    --arg sonnet "$SONNET_MODEL" \
    --arg opus "$OPUS_MODEL" \
    --arg botToken "$TELEGRAM_BOT_TOKEN" \
    --arg userId "$TELEGRAM_USER_ID" \
    --arg gwToken "$GATEWAY_TOKEN" \
'{
  "env": {
    "TELEGRAM_BOT_TOKEN": $botToken
  },
  "models": {
    "providers": {
      "claudible": {
        "baseUrl": $baseUrl,
        "apiKey": $apiKey,
        "api": "openai-completions",
        "models": [
          {
            "id": $sonnet,
            "name": "Claude Sonnet 4.6",
            "api": "openai-completions",
            "reasoning": false,
            "input": ["text", "image"],
            "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 },
            "contextWindow": 200000,
            "maxTokens": 16384
          },
          {
            "id": $opus,
            "name": "Claude Opus 4.6",
            "api": "openai-completions",
            "reasoning": false,
            "input": ["text", "image"],
            "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 },
            "contextWindow": 200000,
            "maxTokens": 16384
          },
          {
            "id": $haiku,
            "name": "Claude Haiku 4.5",
            "api": "openai-completions",
            "reasoning": false,
            "input": ["text", "image"],
            "cost": { "input": 0, "output": 0, "cacheRead": 0, "cacheWrite": 0 },
            "contextWindow": 200000,
            "maxTokens": 16384
          }
        ]
      }
    }
  },
  "agents": {
    "defaults": {
      "model": {
        "primary": ("claudible/" + $opus)
      },
      "maxConcurrent": 4,
      "subagents": {
        "maxConcurrent": 8
      }
    }
  },
  "messages": {
    "ackReactionScope": "group-mentions"
  },
  "commands": {
    "native": "auto",
    "nativeSkills": "auto"
  },
  "channels": {
    "telegram": {
      "enabled": true,
      "dmPolicy": "pairing",
      "allowFrom": [$userId],
      "groupPolicy": "allowlist",
      "streamMode": "block"
    }
  },
  "gateway": {
    "port": 18789,
    "mode": "local",
    "bind": "loopback",
    "auth": {
      "mode": "token",
      "token": $gwToken
    },
    "tailscale": {
      "mode": "off",
      "resetOnExit": false
    }
  },
  "plugins": {
    "entries": {
      "telegram": {
        "enabled": true
      }
    }
  }
}' > "$CONFIG_FILE"

chmod 600 "$CONFIG_FILE"

echo "  ${GREEN}Created $CONFIG_FILE${NC}"
echo ""

echo "${GREEN}================================${NC}"
echo "${GREEN}  Configuration Complete!${NC}"
echo "${GREEN}================================${NC}"
echo ""
echo "OpenClaw is configured to use Claudible:"
echo "  Config:   ${BLUE}$CONFIG_FILE${NC}"
echo "  Endpoint: ${BLUE}$BASE_API_URL${NC}"
echo "  API Key:  ${BLUE}${MASKED_KEY}...${NC}"
echo "  Bot:      ${BLUE}${MASKED_BOT}${NC}"
echo "  User ID:  ${BLUE}$TELEGRAM_USER_ID${NC}"
echo ""
# Auto-restart gateway
if command -v openclaw >/dev/null 2>&1; then
    echo "${BLUE}Restarting gateway...${NC}"
    if openclaw gateway restart 2>/dev/null; then
        echo "  ${GREEN}Gateway restarted successfully${NC}"
    else
        echo "  ${YELLOW}Gateway restart failed. You may need to restart manually:${NC}"
        echo "    ${BLUE}openclaw gateway restart${NC}"
    fi
else
    echo "${YELLOW}Note: openclaw not found on PATH. Please restart the gateway manually:${NC}"
    echo "  ${BLUE}openclaw gateway restart${NC}"
fi
echo ""
echo "${YELLOW}Next steps:${NC}"
echo "  1. Open Telegram and send a message to your bot"
echo ""
echo "  Documentation: ${BLUE}$ENDPOINT_URL/docs/openclaw${NC}"
echo ""
