#!/bin/bash
# check-approvals.sh - Check for items needing Michael's approval
# Sends formatted approval requests to Telegram
#
# Usage: ./check-approvals.sh
# Cron: 0 8,12,17 * * * /home/clawd/scripts/check-approvals.sh

set -e

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

echo "Checking for items needing approval..."

# Fetch items with Needs Approval = true
APPROVALS=$(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": {
            "property": "Needs Approval",
            "checkbox": {"equals": true}
        },
        "sorts": [{"property": "Priority", "direction": "ascending"}]
    }')

# Count approvals
APPROVAL_COUNT=$(echo "$APPROVALS" | python3 -c "import sys,json; print(len(json.load(sys.stdin).get('results',[])))" 2>/dev/null || echo "0")

if [ "$APPROVAL_COUNT" -eq 0 ]; then
    echo "No items need approval"
    exit 0
fi

echo "Found $APPROVAL_COUNT item(s) needing approval"

# Format message for Telegram
MESSAGE="⏳ *APPROVAL NEEDED* ($APPROVAL_COUNT items)

"

# Add each item
MESSAGE+=$(echo "$APPROVALS" | python3 -c "
import sys, json
data = json.load(sys.stdin)
items = []
for r in data.get('results', []):
    title = r.get('properties', {}).get('Task', {}).get('title', [{}])[0].get('text', {}).get('content', 'Unknown')
    priority = r.get('properties', {}).get('Priority', {}).get('select', {}).get('name', 'P2')
    task_type = r.get('properties', {}).get('Type', {}).get('select', {}).get('name', 'Task')
    notes = r.get('properties', {}).get('Notes', {}).get('rich_text', [{}])[0].get('text', {}).get('content', '')[:100]
    url = r.get('url', '')

    item = f'*{priority}* {title}\n'
    item += f'Type: {task_type}\n'
    if notes:
        item += f'Notes: {notes}...\n'
    item += f'[Open in Notion]({url})\n'
    items.append(item)
print('\n'.join(items))
")

MESSAGE+="
Reply with task name + APPROVE or REJECT"

# Send to Telegram
curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
    -d chat_id="$TELEGRAM_CHAT_ID" \
    -d text="$MESSAGE" \
    -d parse_mode="Markdown" \
    -d disable_web_page_preview="true" \
    > /dev/null

echo "Approval request sent to Telegram"
