#!/bin/bash
# morning-brief.sh - Send morning brief to Telegram at 6am Sydney
# Cron (UTC): 0 19 * * * /home/clawd/scripts/morning-brief.sh
# (6am Sydney AEDT = 7pm UTC previous day, adjust for daylight savings)

set -e

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

TODAY=$(date +"%b %d, %Y")
YESTERDAY=$(date -d "yesterday" +"%Y-%m-%d" 2>/dev/null || date -v-1d +"%Y-%m-%d")

echo "Generating morning brief for $TODAY..."

# ===== 1. FETCH SYSTEM STATE =====
echo "Fetching system state..."
SYSTEM_STATE=$(curl -s -X POST "https://api.notion.com/v1/databases/${SYSTEM_STATE_DB}/query" \
    -H "Authorization: Bearer $NOTION_API_KEY" \
    -H "Content-Type: application/json" \
    -H "Notion-Version: 2022-06-28" \
    -d '{}')

# Parse system statuses
GROWTH_STATUS=$(echo "$SYSTEM_STATE" | jq -r '.results[] | select(.properties.System.title[0].text.content == "Growth Engine") | .properties.Status.select.name // "Unknown"')
PLATFORM_STATUS=$(echo "$SYSTEM_STATE" | jq -r '.results[] | select(.properties.System.title[0].text.content == "Main Platform") | .properties.Status.select.name // "Unknown"')
VPS_STATUS=$(echo "$SYSTEM_STATE" | jq -r '.results[] | select(.properties.System.title[0].text.content == "VPS") | .properties.Status.select.name // "Unknown"')
CLAWDBOT_STATUS=$(echo "$SYSTEM_STATE" | jq -r '.results[] | select(.properties.System.title[0].text.content == "Clawdbot") | .properties.Status.select.name // "Unknown"')

# ===== 2. FETCH PIPELINE STATS =====
echo "Fetching pipeline stats..."
STATS=$(curl -s "${GROWTH_ENGINE_API}/api/dashboard/stats" 2>/dev/null || echo '{}')

TOTAL_LEADS=$(echo "$STATS" | jq -r '.totalLeads // 0')
HOT_LEADS=$(echo "$STATS" | jq -r '.hotLeads // 0')
PIPELINE_VALUE=$(echo "$STATS" | jq -r '.pipelineValue // 0')
CALLS_YESTERDAY=$(echo "$STATS" | jq -r '.callsYesterday // 0')

# ===== 3. FETCH HOT LEADS =====
echo "Fetching hot leads..."
HOT_LEADS_DATA=$(curl -s "${GROWTH_ENGINE_API}/api/leads?status=hot&limit=5" 2>/dev/null || echo '{"leads":[]}')
HOT_LEAD_NAMES=$(echo "$HOT_LEADS_DATA" | jq -r '.leads[].company_name // .leads[].name' | head -3 | tr '\n' ', ' | sed 's/,$//')

# Check for stale hot leads (no contact in 48hrs)
STALE_WARNING=""
STALE_COUNT=$(echo "$HOT_LEADS_DATA" | jq '[.leads[] | select(.last_contact_at != null) | select((now - (.last_contact_at | fromdateiso8601)) > 172800)] | length')
if [ "$STALE_COUNT" -gt 0 ]; then
    STALE_WARNING=" (⚠️ $STALE_COUNT stale - last contact >48hrs)"
fi

# ===== 4. FETCH OVERNIGHT DEPLOYS =====
echo "Fetching overnight deploys..."
DEPLOYS=$(curl -s -X POST "https://api.notion.com/v1/databases/${DEPLOY_LOG_DB}/query" \
    -H "Authorization: Bearer $NOTION_API_KEY" \
    -H "Content-Type: application/json" \
    -H "Notion-Version: 2022-06-28" \
    -d "{
        \"filter\": {
            \"property\": \"Date\",
            \"date\": {
                \"on_or_after\": \"$YESTERDAY\"
            }
        },
        \"sorts\": [{\"property\": \"Date\", \"direction\": \"descending\"}]
    }")

DEPLOY_LIST=$(echo "$DEPLOYS" | jq -r '.results[] | "- CC deployed: \(.properties.Deploy.title[0].text.content // "Unknown") (\(.properties.Type.select.name // "Unknown") tier)"' | head -3)
if [ -z "$DEPLOY_LIST" ]; then
    DEPLOY_LIST="- No deploys overnight"
fi

# ===== 5. FETCH NEW TASKS =====
echo "Fetching new tasks..."
NEW_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\": \"Source\", \"select\": {\"equals\": \"Slack\"}},
                {\"timestamp\": \"created_time\", \"created_time\": {\"on_or_after\": \"$YESTERDAY\"}}
            ]
        }
    }")

NEW_TASK_COUNT=$(echo "$NEW_TASKS" | jq '.results | length')
NEW_TASK_LIST=$(echo "$NEW_TASKS" | jq -r '.results[] | "- \(.properties.Task.title[0].text.content // "Unknown")"' | head -3)
if [ "$NEW_TASK_COUNT" -gt 0 ]; then
    OVERNIGHT_TASKS="- $NEW_TASK_COUNT new task(s) from Slack"
else
    OVERNIGHT_TASKS="- No new tasks from Slack"
fi

# ===== 6. FETCH PENDING APPROVALS =====
echo "Fetching pending approvals..."
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}
        }
    }')

APPROVAL_LIST=$(echo "$APPROVALS" | jq -r '.results[] | "- \(.properties.Task.title[0].text.content // "Unknown")"' | head -3)
if [ -z "$APPROVAL_LIST" ]; then
    APPROVAL_LIST="- [None today]"
fi

# ===== 7. FETCH TODAY'S PRIORITIES =====
echo "Fetching priorities..."
PRIORITIES=$(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": [
                {"or": [
                    {"property": "Priority", "select": {"equals": "P0 Critical"}},
                    {"property": "Priority", "select": {"equals": "P1 High"}}
                ]},
                {"property": "Status", "select": {"does_not_equal": "Done"}}
            ]
        },
        "sorts": [{"property": "Priority", "direction": "ascending"}]
    }')

PRIORITY_LIST=$(echo "$PRIORITIES" | jq -r '.results[:3][] | "- \(.properties.Task.title[0].text.content // "Unknown")"')
if [ -z "$PRIORITY_LIST" ]; then
    PRIORITY_LIST="- No P0/P1 tasks pending"
fi

# ===== 8. GENERATE INSIGHT =====
echo "Generating insight..."
CONTEXT="Pipeline: $TOTAL_LEADS leads, $HOT_LEADS hot, \$$PIPELINE_VALUE value, $CALLS_YESTERDAY calls yesterday. Hot leads: $HOT_LEAD_NAMES"

INSIGHT_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-5-sonnet-20241022\",
        \"max_tokens\": 100,
        \"messages\": [{
            \"role\": \"user\",
            \"content\": \"Based on this sales pipeline data, give ONE actionable insight for today (max 2 sentences). Data: $CONTEXT\"
        }]
    }")

INSIGHT=$(echo "$INSIGHT_RESPONSE" | jq -r '.content[0].text // "Focus on hot leads today."')

# ===== 9. BUILD MESSAGE =====
MESSAGE="☀️ *MORNING BRIEF* | $TODAY

📊 *SYSTEM STATUS*
- Growth Engine: $GROWTH_STATUS
- Main Platform: $PLATFORM_STATUS
- Clawdbot: $CLAWDBOT_STATUS
- VPS: $VPS_STATUS

📈 *PIPELINE SNAPSHOT*
- Total leads: $TOTAL_LEADS
- Hot leads: $HOT_LEADS$STALE_WARNING
- Pipeline value: \$$PIPELINE_VALUE
- Calls yesterday: $CALLS_YESTERDAY

🌙 *OVERNIGHT ACTIVITY*
$DEPLOY_LIST
$OVERNIGHT_TASKS

⏳ *NEEDS YOUR DECISION*
$APPROVAL_LIST

🎯 *TODAY'S PRIORITIES*
$PRIORITY_LIST

💡 *INSIGHT*
$INSIGHT"

# ===== 10. SEND TO TELEGRAM =====
echo "Sending 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" \
    > /dev/null

echo "Morning brief sent at $(date)"
