#!/bin/bash
# Create PostHog insight with correct InsightVizNode format
# Usage: ./create-insight.sh DASHBOARD_ID NAME EVENT_NAME [DISPLAY] [PROJECT_ID]

POSTHOG_KEY=$(cat ~/.config/posthog/api-key 2>/dev/null)
if [ -z "$POSTHOG_KEY" ]; then
  echo "Error: PostHog API key not found at ~/.config/posthog/api-key"
  exit 1
fi

DASHBOARD_ID=$1
NAME=$2
EVENT_NAME=$3
DISPLAY=${4:-ActionsLineGraph}
PROJECT_ID=${5:-316683}

if [ -z "$DASHBOARD_ID" ] || [ -z "$NAME" ] || [ -z "$EVENT_NAME" ]; then
  echo "Usage: $0 DASHBOARD_ID NAME EVENT_NAME [DISPLAY] [PROJECT_ID]"
  echo ""
  echo "Example:"
  echo "  $0 1287840 'Products Created' product_created ActionsLineGraph"
  echo ""
  echo "Display types:"
  echo "  ActionsLineGraph  - Time series (default)"
  echo "  BoldNumber        - Single metric"
  echo "  ActionsBarValue   - Comparison bars"
  echo "  ActionsPie        - Pie chart"
  exit 1
fi

echo "Creating insight: $NAME -> event: $EVENT_NAME"

curl -s -X POST -H "Authorization: Bearer $POSTHOG_KEY" \
  -H "Content-Type: application/json" \
  -d "{
    \"name\": \"$NAME\",
    \"dashboards\": [$DASHBOARD_ID],
    \"query\": {
      \"kind\": \"InsightVizNode\",
      \"source\": {
        \"kind\": \"TrendsQuery\",
        \"series\": [{
          \"kind\": \"EventsNode\",
          \"math\": \"total\",
          \"name\": \"$NAME\",
          \"event\": \"$EVENT_NAME\"
        }],
        \"interval\": \"day\",
        \"dateRange\": {\"date_from\": \"-30d\"},
        \"trendsFilter\": {\"display\": \"$DISPLAY\"},
        \"version\": 2
      }
    }
  }" \
  "https://us.posthog.com/api/projects/$PROJECT_ID/insights/" | jq '{id, name, short_id}'
