#!/bin/bash
# agent-status.sh - Update AI Agent status in Notion
# Usage: ./agent-status.sh "AgentName" "Online|Offline|Error" "Current Task" ["Notes"]

set -e

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

AGENT_NAME="$1"
STATUS="$2"
CURRENT_TASK="$3"
NOTES="${4:-}"

if [ -z "$AGENT_NAME" ] || [ -z "$STATUS" ]; then
    echo "Usage: $0 AgentName Online|Offline|Error \"Current Task\" [\"Notes\"]"
    exit 1
fi

# Map status to emoji format
case "$STATUS" in
    Online)
        STATUS_VALUE="🟢 Online"
        ;;
    Offline)
        STATUS_VALUE="⚫ Offline"
        ;;
    Error)
        STATUS_VALUE="🔴 Error"
        ;;
    *)
        STATUS_VALUE="$STATUS"
        ;;
esac

# Get current timestamp in ISO format
TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%S.000Z")

# First, search for the agent's page in AI Agents database
SEARCH_RESULT=$(curl -s -X POST "https://api.notion.com/v1/databases/${AI_AGENTS_DB}/query" \
    -H "Authorization: Bearer $NOTION_API_KEY" \
    -H "Content-Type: application/json" \
    -H "Notion-Version: 2022-06-28" \
    -d "{
        \"filter\": {
            \"property\": \"Agent\",
            \"title\": {
                \"equals\": \"$AGENT_NAME\"
            }
        }
    }")

# Extract page ID from result
PAGE_ID=$(echo "$SEARCH_RESULT" | jq -r '.results[0].id // empty')

if [ -z "$PAGE_ID" ]; then
    echo "Agent '$AGENT_NAME' not found in AI Agents database"
    exit 1
fi

# Build properties JSON
PROPERTIES="{
    \"Status\": { \"select\": { \"name\": \"$STATUS_VALUE\" } },
    \"Last Active\": { \"date\": { \"start\": \"$TIMESTAMP\" } }
}"

# Add Current Task if provided
if [ -n "$CURRENT_TASK" ]; then
    PROPERTIES=$(echo "$PROPERTIES" | jq ". + {\"Current Task\": { \"rich_text\": [{ \"text\": { \"content\": \"$CURRENT_TASK\" } }] }}")
fi

# Add Notes if provided
if [ -n "$NOTES" ]; then
    PROPERTIES=$(echo "$PROPERTIES" | jq ". + {\"Notes\": { \"rich_text\": [{ \"text\": { \"content\": \"$NOTES\" } }] }}")
fi

# Update the page
curl -s -X PATCH "https://api.notion.com/v1/pages/$PAGE_ID" \
    -H "Authorization: Bearer $NOTION_API_KEY" \
    -H "Content-Type: application/json" \
    -H "Notion-Version: 2022-06-28" \
    -d "{\"properties\": $PROPERTIES}" \
    > /dev/null

echo "Updated $AGENT_NAME: $STATUS_VALUE"
