#!/bin/bash
# Fix PostHog insight to use correct InsightVizNode format
# Usage: ./fix-insight.sh INSIGHT_ID 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

INSIGHT_ID=$1
EVENT_NAME=$2
DISPLAY=${3:-ActionsLineGraph}
PROJECT_ID=${4:-316683}

if [ -z "$INSIGHT_ID" ] || [ -z "$EVENT_NAME" ]; then
  echo "Usage: $0 INSIGHT_ID EVENT_NAME [DISPLAY] [PROJECT_ID]"
  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 "Fixing insight $INSIGHT_ID -> event: $EVENT_NAME, display: $DISPLAY"

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