#!/bin/bash
# add-telegram-group.sh
# One-command setup for a new OpenClaw Telegram group
#
# Usage:
#   ./add-telegram-group.sh <chat_id> <group-name> [--mention]
#
# Examples:
#   ./add-telegram-group.sh -1001234567890 nmc-ops
#   ./add-telegram-group.sh -1001234567890 family --mention   (Harvey only responds when @mentioned)
#
# To get the chat ID: add Harvey to the group, then check gateway logs:
#   openclaw gateway logs | grep "chat_id"
# Or just message the group and I'll tell you the ID.

set -e

CONFIG="$HOME/.openclaw/openclaw.json"
BACKUP_DIR="$HOME/.openclaw/config-backups"
WORKSPACE="$HOME/.openclaw/workspace"
MEMORY_DIR="$WORKSPACE/memory/channels"
DEFAULT_MODEL="anthropic/claude-sonnet-4-6"

# --- Args ---
CHAT_ID="$1"
GROUP_NAME="$2"
REQUIRE_MENTION="false"
if [[ "$3" == "--mention" ]]; then
  REQUIRE_MENTION="true"
fi

if [[ -z "$CHAT_ID" || -z "$GROUP_NAME" ]]; then
  echo "Usage: $0 <chat_id> <group-name> [--mention]"
  echo ""
  echo "  chat_id     Telegram group ID (negative number, e.g. -1001234567890)"
  echo "  group-name  Short slug for memory file (e.g. family, nmc-ops, alerts)"
  echo "  --mention   Harvey only responds when @mentioned (default: responds to all)"
  exit 1
fi

# --- Validate chat ID format ---
if [[ ! "$CHAT_ID" =~ ^-[0-9]+$ ]]; then
  echo "❌ Chat ID should be a negative number (e.g. -1001234567890)"
  exit 1
fi

echo "🔧 Setting up Telegram group: $GROUP_NAME ($CHAT_ID)"
echo "   requireMention: $REQUIRE_MENTION"
echo ""

# --- Backup config ---
mkdir -p "$BACKUP_DIR"
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
BACKUP="$BACKUP_DIR/openclaw-$TIMESTAMP.json"
cp "$CONFIG" "$BACKUP"
echo "✅ Config backed up to: $BACKUP"

# --- Update openclaw.json ---
python3 - <<PYEOF
import json

config_path = "$CONFIG"
chat_id = "$CHAT_ID"
model = "$DEFAULT_MODEL"
require_mention = "$REQUIRE_MENTION" == "true"

with open(config_path) as f:
    config = json.load(f)

tg = config.setdefault("channels", {}).setdefault("telegram", {})

# Add to groups allowlist
groups = tg.setdefault("groups", {})
if chat_id in groups:
    print(f"⚠️  Group {chat_id} already in config — updating requireMention only")
groups[chat_id] = {"requireMention": require_mention}

# Add model override
mbc = config["channels"].setdefault("modelByChannel", {}).setdefault("telegram", {})
mbc[chat_id] = model

with open(config_path, "w") as f:
    json.dump(config, f, indent=2)

print(f"✅ Added {chat_id} to openclaw.json (requireMention={require_mention}, model={model})")
PYEOF

# --- Create channel memory file ---
mkdir -p "$MEMORY_DIR"
MEMORY_FILE="$MEMORY_DIR/telegram-$GROUP_NAME.md"

if [[ -f "$MEMORY_FILE" ]]; then
  echo "⚠️  Memory file already exists: $MEMORY_FILE — skipping"
else
  cat > "$MEMORY_FILE" <<EOF
# Channel Memory: telegram-$GROUP_NAME
# Chat ID: $CHAT_ID
# Created: $(date +%Y-%m-%d)

## Context
<!-- Who's in this group, what it's for -->

## Active Threads
<!-- Ongoing conversations or topics -->

## Open Questions
<!-- Things pending a response or follow-up -->

## Parked
<!-- Items to revisit later -->
EOF
  echo "✅ Created memory file: $MEMORY_FILE"
fi

# --- Restart gateway ---
echo ""
echo "🔄 Restarting gateway..."
openclaw gateway restart
echo ""
echo "✅ Done! Group '$GROUP_NAME' ($CHAT_ID) is live."
echo "   Memory file: $MEMORY_FILE"
echo "   requireMention: $REQUIRE_MENTION"
echo ""
echo "💡 To find a new group's chat ID:"
echo "   openclaw gateway logs | grep 'chat_id' | tail -20"
