#!/bin/bash
# telegram-commands.sh - Handle Telegram commands for Clawdbot
#
# Commands:
#   /tasks  - List pending CC tasks from Work Tracker
#   /run    - Trigger CC to work on highest priority task
#   /run all - Trigger CC to work through all pending tasks
#   /status - Check if CC is currently running
#   /stop   - Kill CC process if stuck
#   /health - Quick system health check
#   /bp <description> - Create bug with 6-stage protocol template
#   /fp <description> - Create feature with 6-stage protocol template
#   /p - Protocol check (is DEV following the protocol?)
#   /audit - Full audit before marking complete
#
# Run as daemon: ./telegram-commands.sh daemon
# Run once: ./telegram-commands.sh

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/config.env"

OFFSET_FILE="/tmp/telegram_offset"
LOG_FILE="/var/log/clawdbot/telegram-commands.log"
PID_FILE="/tmp/claude-code.pid"

mkdir -p /var/log/clawdbot

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$LOG_FILE"
}

send_message() {
    local text="$1"
    curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
        -d chat_id="$TELEGRAM_CHAT_ID" \
        -d text="$text" \
        -d parse_mode="Markdown" \
        > /dev/null 2>&1
}

get_updates() {
    local offset=""
    if [ -f "$OFFSET_FILE" ]; then
        offset=$(cat "$OFFSET_FILE")
    fi

    curl -s "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/getUpdates?offset=$offset&timeout=30" 2>/dev/null
}

handle_tasks() {
    log "Handling /tasks command"

    # Query Work Tracker for pending tasks
    TASKS=$(curl -s -X POST "https://api.notion.com/v1/databases/${WORK_TRACKER_DB}/query" \
        -H "Authorization: Bearer $NOTION_API_KEY" \
        -H "Content-Type: application/json" \
        -H "Notion-Version: 2022-06-28" \
        -d '{"filter":{"and":[{"property":"Status","select":{"does_not_equal":"Done"}},{"property":"Status","select":{"does_not_equal":"Cancelled"}}]},"sorts":[{"property":"Priority","direction":"ascending"}],"page_size":10}' 2>/dev/null)

    # Parse and format tasks (pass via env var since heredoc takes stdin)
    export TASKS_JSON="$TASKS"
    MESSAGE=$(python3 << 'PYEOF'
import os
import json

try:
    data = json.loads(os.environ.get('TASKS_JSON', '{}'))
    results = data.get('results', [])

    if not results:
        print("📋 *No pending tasks*\n\nAll caught up!")
        sys.exit(0)

    lines = ["📋 *Pending Tasks*\n"]

    for r in results[:10]:
        props = r.get('properties', {})

        # Title
        title_arr = props.get('Task', {}).get('title', [])
        title = title_arr[0].get('text', {}).get('content', 'Untitled') if title_arr else 'Untitled'

        # Priority
        priority = props.get('Priority', {}).get('select', {})
        priority_name = priority.get('name', '?') if priority else '?'

        # Status
        status = props.get('Status', {}).get('status', {})
        status_name = status.get('name', '?') if status else '?'

        # Owner
        owner_select = props.get('Owner', {}).get('select', {})
        owner = owner_select.get('name', 'Unassigned') if owner_select else 'Unassigned'

        # Format line
        emoji = "🔴" if priority_name == "P0" else "🟠" if priority_name == "P1" else "🟡" if priority_name == "P2" else "⚪"
        lines.append(f"{emoji} [{priority_name}] {title[:40]}")
        lines.append(f"   Status: {status_name} | Owner: {owner}")
        lines.append("")

    lines.append("Use `/run` to start highest priority")
    lines.append("Use `/run all` to work through all")

    print('\n'.join(lines))
except Exception as e:
    print(f"Error fetching tasks: {e}")
PYEOF
)

    send_message "$MESSAGE"
}

handle_run() {
    local mode="${1:-next}"
    log "Handling /run command with mode: $mode"

    # Trigger CC
    "$SCRIPT_DIR/trigger-cc.sh" "$mode" &
}

handle_status() {
    log "Handling /status command"

    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        if ps -p "$PID" > /dev/null 2>&1; then
            # Get runtime
            START=$(ps -o lstart= -p "$PID" 2>/dev/null)
            OUTPUT=$(tail -5 /tmp/cc-output.txt 2>/dev/null || echo "No output yet")

            send_message "🟢 *Claude Code Running*

PID: \`$PID\`
Started: $START

*Recent output:*
\`\`\`
$OUTPUT
\`\`\`

Use \`/stop\` to kill if stuck"
        else
            rm -f "$PID_FILE"
            send_message "⚪ *Claude Code Stopped*

No active CC process.
Use \`/run\` to start."
        fi
    else
        send_message "⚪ *Claude Code Stopped*

No active CC process.
Use \`/run\` to start."
    fi
}

handle_stop() {
    log "Handling /stop command"

    if [ -f "$PID_FILE" ]; then
        PID=$(cat "$PID_FILE")
        if ps -p "$PID" > /dev/null 2>&1; then
            kill -9 "$PID" 2>/dev/null || true
            rm -f "$PID_FILE"
            send_message "🛑 *Claude Code Killed*

Process $PID terminated.
Use \`/run\` to restart."
            log "Killed CC process $PID"
        else
            rm -f "$PID_FILE"
            send_message "⚪ CC was not running (stale PID file removed)"
        fi
    else
        send_message "⚪ CC is not running"
    fi
}

handle_cc() {
    local message="$1"
    log "Handling /cc command: $message"

    send_message "🤖 *Asking Claude Code...*"

    # Run CC relay and capture output
    OUTPUT=$("$SCRIPT_DIR/cc-relay.sh" "$message" 2>&1 | tail -50)

    if [ -n "$OUTPUT" ]; then
        # Truncate if too long for Telegram (4096 char limit)
        if [ ${#OUTPUT} -gt 3500 ]; then
            OUTPUT="${OUTPUT:0:3500}...

(truncated - full output in /tmp/cc-relay-output.txt)"
        fi
        send_message "🤖 *Claude Code:*

$OUTPUT"
    else
        send_message "⚠️ CC returned no output. Check /tmp/cc-relay-output.txt"
    fi
}

handle_bp() {
    local description="$1"
    log "Handling /bp command: $description"

    send_message "🐛 Creating bug report..."

    # Template source: templates/bug-template.json
    # To edit the template, modify that JSON file
    # Escape description for JSON
    ESCAPED_DESC=$(echo "$description" | sed 's/"/\\"/g' | sed 's/\n/\\n/g')

    RESPONSE=$(curl -s -X POST "https://api.notion.com/v1/pages" \
        -H "Authorization: Bearer $NOTION_API_KEY" \
        -H "Content-Type: application/json" \
        -H "Notion-Version: 2022-06-28" \
        -d "{
            \"parent\": {\"database_id\": \"$WORK_TRACKER_DB\"},
            \"properties\": {
                \"Task\": {\"title\": [{\"text\": {\"content\": \"BUG: $ESCAPED_DESC\"}}]},
                \"Type\": {\"select\": {\"name\": \"Bug\"}},
                \"Owner\": {\"select\": {\"name\": \"DEV\"}},
                \"Priority\": {\"select\": {\"name\": \"P1 High\"}},
                \"Status\": {\"select\": {\"name\": \"To Do\"}},
                \"Source\": {\"select\": {\"name\": \"Telegram\"}},
                \"Notes\": {\"rich_text\": [{\"text\": {\"content\": \"Issue: $ESCAPED_DESC\\n\\nReported via Telegram. DEV: Follow DEV.md protocol.\"}}]}
            }
        }" 2>/dev/null)

    # Get page ID
    PAGE_ID=$(echo "$RESPONSE" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)

    if [ -n "$PAGE_ID" ]; then
        # Add template content to page (matches DEV.md Bug Protocol)
        # Include the bug description in the page body
        curl -s -X PATCH "https://api.notion.com/v1/blocks/$PAGE_ID/children" \
            -H "Authorization: Bearer $NOTION_API_KEY" \
            -H "Content-Type: application/json" \
            -H "Notion-Version: 2022-06-28" \
            -d "{
                \"children\": [
                    {\"type\": \"callout\", \"callout\": {\"rich_text\": [{\"text\": {\"content\": \"$ESCAPED_DESC\"}}], \"icon\": {\"emoji\": \"🐛\"}}},
                    {\"type\": \"callout\", \"callout\": {\"rich_text\": [{\"text\": {\"content\": \"DEV: Read DEV.md. Use Memory for working state. Sync here at checkpoints.\"}}], \"icon\": {\"emoji\": \"💾\"}}},
                    {\"type\": \"heading_2\", \"heading_2\": {\"rich_text\": [{\"text\": {\"content\": \"1. START\"}}]}},
                    {\"type\": \"to_do\", \"to_do\": {\"rich_text\": [{\"text\": {\"content\": \"Read DEV.md protocol\"}}], \"checked\": false}},
                    {\"type\": \"to_do\", \"to_do\": {\"rich_text\": [{\"text\": {\"content\": \"Read docs/LESSONS.md\"}}], \"checked\": false}},
                    {\"type\": \"paragraph\", \"paragraph\": {\"rich_text\": [{\"text\": {\"content\": \"Relevant lessons: \"}}]}},
                    {\"type\": \"heading_2\", \"heading_2\": {\"rich_text\": [{\"text\": {\"content\": \"2. INVESTIGATE\"}}]}},
                    {\"type\": \"paragraph\", \"paragraph\": {\"rich_text\": [{\"text\": {\"content\": \"Reproduce steps: \"}}]}},
                    {\"type\": \"paragraph\", \"paragraph\": {\"rich_text\": [{\"text\": {\"content\": \"Expected: \"}}]}},
                    {\"type\": \"paragraph\", \"paragraph\": {\"rich_text\": [{\"text\": {\"content\": \"Actual: \"}}]}},
                    {\"type\": \"paragraph\", \"paragraph\": {\"rich_text\": [{\"text\": {\"content\": \"Hypothesis: \"}}]}},
                    {\"type\": \"heading_2\", \"heading_2\": {\"rich_text\": [{\"text\": {\"content\": \"3. FIX ATTEMPTS\"}}]}},
                    {\"type\": \"paragraph\", \"paragraph\": {\"rich_text\": [{\"text\": {\"content\": \"1. Tried: ___ | Result: ___\"}}]}},
                    {\"type\": \"paragraph\", \"paragraph\": {\"rich_text\": [{\"text\": {\"content\": \"2. Tried: ___ | Result: ___\"}}]}},
                    {\"type\": \"heading_2\", \"heading_2\": {\"rich_text\": [{\"text\": {\"content\": \"4. SOLUTION\"}}]}},
                    {\"type\": \"paragraph\", \"paragraph\": {\"rich_text\": [{\"text\": {\"content\": \"What fixed it: \"}}]}},
                    {\"type\": \"paragraph\", \"paragraph\": {\"rich_text\": [{\"text\": {\"content\": \"Root cause: \"}}]}},
                    {\"type\": \"heading_2\", \"heading_2\": {\"rich_text\": [{\"text\": {\"content\": \"5. VERIFY\"}}]}},
                    {\"type\": \"to_do\", \"to_do\": {\"rich_text\": [{\"text\": {\"content\": \"Tested locally\"}}], \"checked\": false}},
                    {\"type\": \"to_do\", \"to_do\": {\"rich_text\": [{\"text\": {\"content\": \"Tested live\"}}], \"checked\": false}},
                    {\"type\": \"to_do\", \"to_do\": {\"rich_text\": [{\"text\": {\"content\": \"Tried to break it\"}}], \"checked\": false}},
                    {\"type\": \"heading_2\", \"heading_2\": {\"rich_text\": [{\"text\": {\"content\": \"6. RECORD\"}}]}},
                    {\"type\": \"to_do\", \"to_do\": {\"rich_text\": [{\"text\": {\"content\": \"Added to LESSONS.md\"}}], \"checked\": false}},
                    {\"type\": \"paragraph\", \"paragraph\": {\"rich_text\": [{\"text\": {\"content\": \"Commit: \"}}]}}
                ]
            }" > /dev/null 2>&1

        send_message "✅ *Bug Created*

🐛 $description

📋 Type: Bug
👤 Owner: DEV
🔴 Priority: P1 High

Handing off to DEV..."

        # Trigger DEV to start working on this bug
        "$SCRIPT_DIR/cc-relay.sh" "New bug assigned to you: $description

FIRST: Read DEV.md - you must follow the protocol.

Then:
1. Open the bug page in Work Tracker
2. Store in memory: current_task = this bug
3. Store in memory: stage = INVESTIGATE
4. Follow the 6-stage bug protocol in DEV.md
5. Update the Notion page as you progress

Start now." &

        send_message "🚀 DEV notified and starting work."
        log "Created bug page: $PAGE_ID"
    else
        send_message "❌ Failed to create bug. Check logs."
        log "Failed to create bug: $RESPONSE"
    fi
}

handle_fp() {
    local description="$1"
    log "Handling /fp command: $description"

    send_message "✨ Creating feature..."

    # Template source: templates/feature-template.json
    # To edit the template, modify that JSON file
    # Escape description for JSON
    ESCAPED_DESC=$(echo "$description" | sed 's/"/\\"/g' | sed 's/\n/\\n/g')

    RESPONSE=$(curl -s -X POST "https://api.notion.com/v1/pages" \
        -H "Authorization: Bearer $NOTION_API_KEY" \
        -H "Content-Type: application/json" \
        -H "Notion-Version: 2022-06-28" \
        -d "{
            \"parent\": {\"database_id\": \"$WORK_TRACKER_DB\"},
            \"properties\": {
                \"Task\": {\"title\": [{\"text\": {\"content\": \"FEATURE: $ESCAPED_DESC\"}}]},
                \"Type\": {\"select\": {\"name\": \"Feature\"}},
                \"Owner\": {\"select\": {\"name\": \"DEV\"}},
                \"Priority\": {\"select\": {\"name\": \"P2 Medium\"}},
                \"Status\": {\"select\": {\"name\": \"To Do\"}},
                \"Source\": {\"select\": {\"name\": \"Telegram\"}},
                \"Notes\": {\"rich_text\": [{\"text\": {\"content\": \"Feature: $ESCAPED_DESC\\n\\nRequested via Telegram. DEV: Follow DEV.md protocol.\"}}]}
            }
        }" 2>/dev/null)

    # Get page ID
    PAGE_ID=$(echo "$RESPONSE" | python3 -c "import sys,json; print(json.load(sys.stdin).get('id',''))" 2>/dev/null)

    if [ -n "$PAGE_ID" ]; then
        # Add template content to page (matches DEV.md Feature Protocol)
        # Include the feature description in the page body
        curl -s -X PATCH "https://api.notion.com/v1/blocks/$PAGE_ID/children" \
            -H "Authorization: Bearer $NOTION_API_KEY" \
            -H "Content-Type: application/json" \
            -H "Notion-Version: 2022-06-28" \
            -d "{
                \"children\": [
                    {\"type\": \"callout\", \"callout\": {\"rich_text\": [{\"text\": {\"content\": \"$ESCAPED_DESC\"}}], \"icon\": {\"emoji\": \"✨\"}}},
                    {\"type\": \"callout\", \"callout\": {\"rich_text\": [{\"text\": {\"content\": \"DEV: Read DEV.md. Use Memory for working state. Sync here at checkpoints.\"}}], \"icon\": {\"emoji\": \"💾\"}}},
                    {\"type\": \"heading_2\", \"heading_2\": {\"rich_text\": [{\"text\": {\"content\": \"1. START\"}}]}},
                    {\"type\": \"to_do\", \"to_do\": {\"rich_text\": [{\"text\": {\"content\": \"Read DEV.md protocol\"}}], \"checked\": false}},
                    {\"type\": \"to_do\", \"to_do\": {\"rich_text\": [{\"text\": {\"content\": \"Read docs/LESSONS.md\"}}], \"checked\": false}},
                    {\"type\": \"paragraph\", \"paragraph\": {\"rich_text\": [{\"text\": {\"content\": \"Relevant patterns: \"}}]}},
                    {\"type\": \"heading_2\", \"heading_2\": {\"rich_text\": [{\"text\": {\"content\": \"2. EXPLORE\"}}]}},
                    {\"type\": \"paragraph\", \"paragraph\": {\"rich_text\": [{\"text\": {\"content\": \"Similar features: \"}}]}},
                    {\"type\": \"paragraph\", \"paragraph\": {\"rich_text\": [{\"text\": {\"content\": \"Files to modify: \"}}]}},
                    {\"type\": \"heading_2\", \"heading_2\": {\"rich_text\": [{\"text\": {\"content\": \"3. PLAN\"}}]}},
                    {\"type\": \"to_do\", \"to_do\": {\"rich_text\": [{\"text\": {\"content\": \"Plan recorded below\"}}], \"checked\": false}},
                    {\"type\": \"paragraph\", \"paragraph\": {\"rich_text\": [{\"text\": {\"content\": \"Approach: \"}}]}},
                    {\"type\": \"heading_2\", \"heading_2\": {\"rich_text\": [{\"text\": {\"content\": \"4. BUILD\"}}]}},
                    {\"type\": \"to_do\", \"to_do\": {\"rich_text\": [{\"text\": {\"content\": \"Tests written first\"}}], \"checked\": false}},
                    {\"type\": \"to_do\", \"to_do\": {\"rich_text\": [{\"text\": {\"content\": \"Code complete\"}}], \"checked\": false}},
                    {\"type\": \"paragraph\", \"paragraph\": {\"rich_text\": [{\"text\": {\"content\": \"Commits: \"}}]}},
                    {\"type\": \"heading_2\", \"heading_2\": {\"rich_text\": [{\"text\": {\"content\": \"5. VERIFY\"}}]}},
                    {\"type\": \"to_do\", \"to_do\": {\"rich_text\": [{\"text\": {\"content\": \"Tested locally\"}}], \"checked\": false}},
                    {\"type\": \"to_do\", \"to_do\": {\"rich_text\": [{\"text\": {\"content\": \"Tested live\"}}], \"checked\": false}},
                    {\"type\": \"to_do\", \"to_do\": {\"rich_text\": [{\"text\": {\"content\": \"Tried to break it\"}}], \"checked\": false}},
                    {\"type\": \"to_do\", \"to_do\": {\"rich_text\": [{\"text\": {\"content\": \"Code review passed\"}}], \"checked\": false}},
                    {\"type\": \"heading_2\", \"heading_2\": {\"rich_text\": [{\"text\": {\"content\": \"6. RECORD\"}}]}},
                    {\"type\": \"to_do\", \"to_do\": {\"rich_text\": [{\"text\": {\"content\": \"Docs updated\"}}], \"checked\": false}},
                    {\"type\": \"to_do\", \"to_do\": {\"rich_text\": [{\"text\": {\"content\": \"Added to LESSONS.md if new pattern\"}}], \"checked\": false}}
                ]
            }" > /dev/null 2>&1

        send_message "✅ *Feature Created*

✨ $description

📋 Type: Feature
👤 Owner: DEV
🟡 Priority: P2 Medium

Handing off to DEV..."

        # Trigger DEV to start working on this feature
        "$SCRIPT_DIR/cc-relay.sh" "New feature assigned to you: $description

FIRST: Read DEV.md - you must follow the protocol.

Then:
1. Open the feature page in Work Tracker
2. Store in memory: current_task = this feature
3. Store in memory: stage = EXPLORE
4. Follow the 6-stage feature protocol in DEV.md
5. Update the Notion page as you progress

Start now." &

        send_message "🚀 DEV notified and starting work."
        log "Created feature page: $PAGE_ID"
    else
        send_message "❌ Failed to create feature. Check logs."
        log "Failed to create feature: $RESPONSE"
    fi
}

handle_protocol() {
    log "Handling /p (protocol) command"

    send_message "📋 *Checking Protocol Status...*"

    # Ask DEV to report protocol status - specifically about DEV.md
    OUTPUT=$("$SCRIPT_DIR/cc-relay.sh" "PROTOCOL CHECK - Answer honestly:

1. Have you read DEV.md this session?
2. Are you following the DEV.md protocol?
3. What step of DEV.md are you on? (1-9 for workflow, or 1-6 for bug/feature)

Check your Memory state:
- current_task: ?
- stage: ?
- hypothesis/approach: ?

If you haven't read DEV.md, read it NOW and report back.
If you're not following it, explain why.

Be brief." 2>&1 | tail -30)

    if [ -n "$OUTPUT" ]; then
        if [ ${#OUTPUT} -gt 3500 ]; then
            OUTPUT="${OUTPUT:0:3500}..."
        fi
        send_message "📋 *Protocol Status*

$OUTPUT"
    else
        send_message "⚠️ DEV not responding. May not be running. Use /status to check."
    fi
}

handle_audit() {
    log "Handling /audit command"

    send_message "🔍 *Running Full Audit...*"

    # Get current in-progress tasks assigned to DEV
    TASKS=$(curl -s -X POST "https://api.notion.com/v1/databases/${WORK_TRACKER_DB}/query" \
        -H "Authorization: Bearer $NOTION_API_KEY" \
        -H "Content-Type: application/json" \
        -H "Notion-Version: 2022-06-28" \
        -d '{"filter":{"and":[{"property":"Owner","select":{"equals":"DEV"}},{"property":"Status","select":{"does_not_equal":"Done"}}]},"sorts":[{"property":"Priority","direction":"ascending"}],"page_size":5}' 2>/dev/null)

    # Ask DEV for detailed audit before marking complete
    OUTPUT=$("$SCRIPT_DIR/cc-relay.sh" "AUDIT BEFORE COMPLETE - Be honest:

DEV.MD COMPLIANCE:
- [ ] Did you follow DEV.md protocol?
- [ ] Did you use Memory for working state?
- [ ] Did you sync to Notion at checkpoints?

MEMORY STATE (retrieve and report):
- current_task: ___
- stage: ___

RECORDS:
- [ ] LESSONS.md read at start?
- [ ] Notion page updated with solution?
- [ ] Added to LESSONS.md if you learned something?

VERIFICATION:
- [ ] Tested locally?
- [ ] Tested live?
- [ ] Tried to break it?
- [ ] Code review done?

READY TO COMPLETE?
If ALL boxes checked: Clear Memory, mark Done in Notion.
If ANY box unchecked: What's missing?

List [x] done and [ ] not done." 2>&1 | tail -50)

    if [ -n "$OUTPUT" ]; then
        if [ ${#OUTPUT} -gt 3500 ]; then
            OUTPUT="${OUTPUT:0:3500}..."
        fi
        send_message "🔍 *Audit Results*

$OUTPUT"
    else
        send_message "⚠️ DEV not responding. Use /status to check if running."
    fi
}

handle_health() {
    log "Handling /health command"

    # Quick health check
    API_STATUS=$(curl -s -o /dev/null -w "%{http_code}" "$GROWTH_ENGINE_API/health" 2>/dev/null || echo "000")

    if [ "$API_STATUS" = "200" ]; then
        API_EMOJI="✅"
    else
        API_EMOJI="❌"
    fi

    # Check disk
    DISK=$(df -h / | tail -1 | awk '{print $5}')

    # Check memory
    MEM=$(free -h | grep Mem | awk '{print $3 "/" $2}')

    send_message "🏥 *System Health*

API: $API_EMOJI ($API_STATUS)
Disk: $DISK used
Memory: $MEM

Full check: \`./health-check.sh\`"
}

process_message() {
    local text="$1"
    local chat_id="$2"

    # Only respond to our chat
    if [ "$chat_id" != "$TELEGRAM_CHAT_ID" ]; then
        log "Ignoring message from unknown chat: $chat_id"
        return
    fi

    case "$text" in
        /tasks|/tasks@*)
            handle_tasks
            ;;
        /run|/run@*)
            handle_run "next"
            ;;
        "/run all"|"/run all@"*)
            handle_run "all"
            ;;
        /run\ *)
            # Extract task ID
            TASK_ID=$(echo "$text" | sed 's/\/run //')
            handle_run "$TASK_ID"
            ;;
        /status|/status@*)
            handle_status
            ;;
        /stop|/stop@*)
            handle_stop
            ;;
        /health|/health@*)
            handle_health
            ;;
        /cc\ *)
            # Extract message after /cc
            CC_MESSAGE=$(echo "$text" | sed 's/^\/cc //')
            handle_cc "$CC_MESSAGE"
            ;;
        /bp\ *)
            # Extract bug description after /bp
            BUG_DESC=$(echo "$text" | sed 's/^\/bp //')
            handle_bp "$BUG_DESC"
            ;;
        /fp\ *)
            # Extract feature description after /fp
            FEATURE_DESC=$(echo "$text" | sed 's/^\/fp //')
            handle_fp "$FEATURE_DESC"
            ;;
        /p|/p@*|/protocol|/protocol@*)
            handle_protocol
            ;;
        /audit|/audit@*)
            handle_audit
            ;;
        /help|/help@*)
            send_message "🤖 *Clawdbot Commands*

*Work:*
/tasks - List pending tasks
/run - Work on highest priority
/run all - Work through all
/cc <msg> - Talk to CC directly

*Create:*
/bp <desc> - Create bug (6-stage template)
/fp <desc> - Create feature (6-stage template)

*Protocol:*
/p - Protocol check (is DEV following it?)
/audit - Full audit before marking complete

*System:*
/status - Check CC status
/stop - Kill CC process
/health - Quick health check"
            ;;
        *)
            # Ignore non-commands
            ;;
    esac
}

poll_once() {
    UPDATES=$(get_updates)

    if [ -z "$UPDATES" ]; then
        return
    fi

    # Process each update
    echo "$UPDATES" | python3 << 'PYEOF'
import sys
import json
import subprocess
import os

try:
    data = json.load(sys.stdin)
    results = data.get('result', [])

    offset_file = "/tmp/telegram_offset"

    for update in results:
        update_id = update.get('update_id', 0)

        # Save offset for next poll
        with open(offset_file, 'w') as f:
            f.write(str(update_id + 1))

        message = update.get('message', {})
        text = message.get('text', '')
        chat_id = str(message.get('chat', {}).get('id', ''))

        if text:
            print(f"CMD:{text}|CHAT:{chat_id}")

except Exception as e:
    print(f"Error: {e}", file=sys.stderr)
PYEOF
}

# Main loop
if [ "${1:-}" = "daemon" ]; then
    log "Starting Telegram command daemon"
    send_message "🤖 *Clawdbot Online*\n\nReady for commands. Type /help for options."

    while true; do
        RESULT=$(poll_once 2>/dev/null || echo "")

        # Process any commands found
        echo "$RESULT" | while IFS= read -r line; do
            if [[ "$line" == CMD:* ]]; then
                TEXT=$(echo "$line" | sed 's/CMD:\(.*\)|CHAT:.*/\1/')
                CHAT=$(echo "$line" | sed 's/.*|CHAT://')
                process_message "$TEXT" "$CHAT"
            fi
        done

        sleep 2
    done
else
    # Single poll
    RESULT=$(poll_once 2>/dev/null || echo "")
    echo "$RESULT" | while IFS= read -r line; do
        if [[ "$line" == CMD:* ]]; then
            TEXT=$(echo "$line" | sed 's/CMD:\(.*\)|CHAT:.*/\1/')
            CHAT=$(echo "$line" | sed 's/.*|CHAT://')
            process_message "$TEXT" "$CHAT"
        fi
    done
fi
