#!/bin/bash
# slack-to-notion.sh - Monitor Slack channels and create tasks in Notion
# Runs every 5 minutes via cron: */5 * * * * /home/clawd/scripts/slack-to-notion.sh

set -e

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

# State file to track last processed message timestamps per channel
STATE_FILE="$SCRIPT_DIR/.slack_state"
touch "$STATE_FILE"

# Keywords that trigger task creation
BUG_KEYWORDS="bug|broken|error|crash|fail|not working|issue"
FEATURE_KEYWORDS="feature request|idea|suggestion|would be nice|can we add"
URGENT_KEYWORDS="urgent|critical|down|emergency|asap"

# Function to classify message using Claude Haiku
classify_message() {
    local MESSAGE="$1"

    # Use Claude Haiku for classification
    RESPONSE=$(curl -s -X POST "https://api.anthropic.com/v1/messages" \
        -H "Content-Type: application/json" \
        -H "x-api-key: $ANTHROPIC_API_KEY" \
        -H "anthropic-version: 2023-06-01" \
        -d "{
            \"model\": \"claude-3-haiku-20240307\",
            \"max_tokens\": 100,
            \"messages\": [{
                \"role\": \"user\",
                \"content\": \"Classify this Slack message. Reply with ONLY one of: BUG, FEATURE, or IGNORE (if neither bug nor feature request).\\n\\nMessage: $MESSAGE\"
            }]
        }")

    echo "$RESPONSE" | jq -r '.content[0].text' | tr '[:lower:]' '[:upper:]' | grep -oE 'BUG|FEATURE|IGNORE' | head -1
}

# Function to extract title from message using Claude Haiku
extract_title() {
    local MESSAGE="$1"

    RESPONSE=$(curl -s -X POST "https://api.anthropic.com/v1/messages" \
        -H "Content-Type: application/json" \
        -H "x-api-key: $ANTHROPIC_API_KEY" \
        -H "anthropic-version: 2023-06-01" \
        -d "{
            \"model\": \"claude-3-haiku-20240307\",
            \"max_tokens\": 50,
            \"messages\": [{
                \"role\": \"user\",
                \"content\": \"Extract a short title (max 10 words) for this bug/feature request. Reply with ONLY the title, nothing else.\\n\\nMessage: $MESSAGE\"
            }]
        }")

    echo "$RESPONSE" | jq -r '.content[0].text' | head -1
}

# Function to check for duplicates in Work Tracker
check_duplicate() {
    local TITLE="$1"

    # Search for similar tasks
    SEARCH_RESULT=$(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 '{
            "page_size": 50
        }')

    # Check if any existing task has a similar title (simple substring match)
    EXISTING=$(echo "$SEARCH_RESULT" | jq -r --arg title "$TITLE" '.results[] | select(.properties.Task.title[0].text.content | ascii_downcase | contains($title | ascii_downcase)) | .id' | head -1)

    echo "$EXISTING"
}

# Function to create task in Notion
create_task() {
    local TITLE="$1"
    local TYPE="$2"
    local PRIORITY="$3"
    local NOTES="$4"

    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\": \"$TITLE\" } }] },
                \"Type\": { \"select\": { \"name\": \"$TYPE\" } },
                \"Status\": { \"select\": { \"name\": \"To Do\" } },
                \"Priority\": { \"select\": { \"name\": \"$PRIORITY\" } },
                \"Owner\": { \"select\": { \"name\": \"Claude Code\" } },
                \"Source\": { \"select\": { \"name\": \"Slack\" } },
                \"Notes\": { \"rich_text\": [{ \"text\": { \"content\": \"$NOTES\" } }] }
            }
        }" > /dev/null

    echo "Created task: $TITLE"
}

# Function to react to Slack message
react_to_message() {
    local CHANNEL="$1"
    local TIMESTAMP="$2"

    curl -s -X POST "https://slack.com/api/reactions.add" \
        -H "Authorization: Bearer $SLACK_BOT_TOKEN" \
        -H "Content-Type: application/json" \
        -d "{
            \"channel\": \"$CHANNEL\",
            \"timestamp\": \"$TIMESTAMP\",
            \"name\": \"white_check_mark\"
        }" > /dev/null
}

# Process each monitored channel
IFS=',' read -ra CHANNELS <<< "$SLACK_CHANNELS"

for CHANNEL in "${CHANNELS[@]}"; do
    CHANNEL=$(echo "$CHANNEL" | tr -d ' ')

    # Get last processed timestamp for this channel
    LAST_TS=$(grep "^$CHANNEL:" "$STATE_FILE" | cut -d':' -f2)
    LAST_TS="${LAST_TS:-0}"

    echo "Checking channel $CHANNEL (last: $LAST_TS)..."

    # Fetch recent messages
    MESSAGES=$(curl -s -X GET "https://slack.com/api/conversations.history?channel=$CHANNEL&oldest=$LAST_TS&limit=20" \
        -H "Authorization: Bearer $SLACK_BOT_TOKEN")

    # Check if successful
    OK=$(echo "$MESSAGES" | jq -r '.ok')
    if [ "$OK" != "true" ]; then
        echo "  Failed to fetch messages from $CHANNEL"
        continue
    fi

    # Process each message
    NEW_LAST_TS="$LAST_TS"
    echo "$MESSAGES" | jq -c '.messages[]' | while read -r MSG; do
        MSG_TS=$(echo "$MSG" | jq -r '.ts')
        MSG_TEXT=$(echo "$MSG" | jq -r '.text')
        MSG_USER=$(echo "$MSG" | jq -r '.user')

        # Skip bot messages
        BOT_ID=$(echo "$MSG" | jq -r '.bot_id // empty')
        if [ -n "$BOT_ID" ]; then
            continue
        fi

        echo "  Processing message: ${MSG_TEXT:0:50}..."

        # Classify the message
        CLASSIFICATION=$(classify_message "$MSG_TEXT")

        if [ "$CLASSIFICATION" = "IGNORE" ]; then
            echo "    Ignored (not a bug/feature)"
            continue
        fi

        # Extract title
        TITLE=$(extract_title "$MSG_TEXT")

        if [ -z "$TITLE" ]; then
            TITLE="${MSG_TEXT:0:50}"
        fi

        # Check for duplicates
        DUPLICATE=$(check_duplicate "$TITLE")
        if [ -n "$DUPLICATE" ]; then
            echo "    Skipped (duplicate found)"
            continue
        fi

        # Determine priority
        if echo "$MSG_TEXT" | grep -iEq "$URGENT_KEYWORDS"; then
            PRIORITY="P1 High"
            IS_URGENT=true
        else
            PRIORITY="P2 Medium"
            IS_URGENT=false
        fi

        # Determine type
        if [ "$CLASSIFICATION" = "BUG" ]; then
            TYPE="Bug"
        else
            TYPE="Feature"
        fi

        # Build notes
        SLACK_LINK="https://slack.com/archives/$CHANNEL/p${MSG_TS//./}"
        NOTES="From Slack: $MSG_TEXT

Source: $SLACK_LINK"

        # Create the task
        create_task "$TITLE" "$TYPE" "$PRIORITY" "$NOTES"

        # React to the message
        react_to_message "$CHANNEL" "$MSG_TS"

        # Send Telegram alert if urgent
        if [ "$IS_URGENT" = true ]; then
            "$SCRIPT_DIR/telegram-alert.sh" "URGENT" "New $PRIORITY $TYPE from Slack: $TITLE"
        fi

        # Update newest timestamp
        if (( $(echo "$MSG_TS > $NEW_LAST_TS" | bc -l) )); then
            NEW_LAST_TS="$MSG_TS"
        fi
    done

    # Update state file with newest timestamp
    if [ "$NEW_LAST_TS" != "$LAST_TS" ]; then
        grep -v "^$CHANNEL:" "$STATE_FILE" > "$STATE_FILE.tmp" || true
        echo "$CHANNEL:$NEW_LAST_TS" >> "$STATE_FILE.tmp"
        mv "$STATE_FILE.tmp" "$STATE_FILE"
    fi
done

echo "Slack sync complete at $(date)"
