#!/bin/bash
# ABOUTME: Syncs Grafana dashboards by removing any that no longer have source files
# ABOUTME: Uses Grafana API to clean up orphaned dashboards from the database

set -e

GRAFANA_URL="${GRAFANA_URL:-http://localhost:3000}"
GRAFANA_USER="${GRAFANA_USER:-admin}"
GRAFANA_PASS="${GRAFANA_PASS:-admin}"
DASHBOARD_DIR="./grafana/dashboards"

echo "🔍 Syncing Grafana dashboards..."

# Get all dashboard UIDs from filesystem
echo "📁 Scanning dashboard files in $DASHBOARD_DIR"
FILESYSTEM_UIDS=()
for file in "$DASHBOARD_DIR"/*.json; do
    if [ -f "$file" ]; then
        uid=$(jq -r '.uid // empty' "$file")
        if [ -n "$uid" ]; then
            FILESYSTEM_UIDS+=("$uid")
            echo "  ✓ Found: $uid ($(basename "$file"))"
        fi
    fi
done

echo ""
echo "🌐 Fetching dashboards from Grafana API..."

# Get all dashboards from Grafana
RESPONSE=$(curl -s -u "$GRAFANA_USER:$GRAFANA_PASS" \
    "$GRAFANA_URL/api/search?type=dash-db" || echo "[]")

if [ "$RESPONSE" = "[]" ] || [ -z "$RESPONSE" ]; then
    echo "⚠️  No dashboards found in Grafana or API call failed"
    echo "   Make sure Grafana is running at $GRAFANA_URL"
    exit 1
fi

DELETED_COUNT=0

# Check each dashboard in Grafana
echo "$RESPONSE" | jq -c '.[]' | while read -r dashboard; do
    uid=$(echo "$dashboard" | jq -r '.uid')
    title=$(echo "$dashboard" | jq -r '.title')
    uri=$(echo "$dashboard" | jq -r '.uri')

    # Check if this UID exists in filesystem
    if [[ ! " ${FILESYSTEM_UIDS[@]} " =~ " ${uid} " ]]; then
        echo "🗑️  Deleting orphaned dashboard: $title (uid: $uid)"

        DELETE_RESPONSE=$(curl -s -X DELETE \
            -u "$GRAFANA_USER:$GRAFANA_PASS" \
            "$GRAFANA_URL/api/dashboards/$uri")

        if echo "$DELETE_RESPONSE" | jq -e '.message' > /dev/null 2>&1; then
            echo "   ✓ $(echo "$DELETE_RESPONSE" | jq -r '.message')"
            ((DELETED_COUNT++)) || true
        else
            echo "   ✗ Failed to delete"
        fi
    else
        echo "  ✓ Keeping: $title (uid: $uid)"
    fi
done

echo ""
echo "✅ Sync complete!"
echo "   Dashboards in filesystem: ${#FILESYSTEM_UIDS[@]}"
if [ $DELETED_COUNT -gt 0 ]; then
    echo "   Deleted from Grafana: $DELETED_COUNT"
else
    echo "   No orphaned dashboards found"
fi
