#!/bin/bash

# SigNoz Dashboard Importer for Bakery IA
# This script imports all SigNoz dashboards into your SigNoz instance

# Configuration
SIGNOZ_HOST="localhost"
SIGNOZ_PORT="3301"
SIGNOZ_API_KEY=""  # Add your API key if authentication is required
DASHBOARDS_DIR="infrastructure/signoz/dashboards"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'  # No Color

# Function to display help
show_help() {
    echo "Usage: $0 [options]"
    echo ""
    echo "Options:
    -h, --host        SigNoz host (default: localhost)
    -p, --port        SigNoz port (default: 3301)
    -k, --api-key     SigNoz API key (if required)
    -d, --dir         Dashboards directory (default: infrastructure/signoz/dashboards)
    -h, --help        Show this help message"
    echo ""
    echo "Example:
    $0 --host signoz.example.com --port 3301 --api-key your-api-key"
}

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -h|--host)
            SIGNOZ_HOST="$2"
            shift 2
            ;;
        -p|--port)
            SIGNOZ_PORT="$2"
            shift 2
            ;;
        -k|--api-key)
            SIGNOZ_API_KEY="$2"
            shift 2
            ;;
        -d|--dir)
            DASHBOARDS_DIR="$2"
            shift 2
            ;;
        --help)
            show_help
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            show_help
            exit 1
            ;;
    esac
done

# Check if dashboards directory exists
if [ ! -d "$DASHBOARDS_DIR" ]; then
    echo -e "${RED}Error: Dashboards directory not found: $DASHBOARDS_DIR${NC}"
    exit 1
fi

# Check if jq is installed for JSON validation
if ! command -v jq &> /dev/null; then
    echo -e "${YELLOW}Warning: jq not found. Skipping JSON validation.${NC}"
    VALIDATE_JSON=false
else
    VALIDATE_JSON=true
fi

# Function to validate JSON
validate_json() {
    local file="$1"
    if [ "$VALIDATE_JSON" = true ]; then
        if ! jq empty "$file" &> /dev/null; then
            echo -e "${RED}Error: Invalid JSON in file: $file${NC}"
            return 1
        fi
    fi
    return 0
}

# Function to import a single dashboard
import_dashboard() {
    local file="$1"
    local filename=$(basename "$file")
    local dashboard_name=$(jq -r '.name' "$file" 2>/dev/null || echo "Unknown")
    
    echo -e "${BLUE}Importing dashboard: $dashboard_name ($filename)${NC}"
    
    # Prepare curl command
    local curl_cmd="curl -s -X POST http://$SIGNOZ_HOST:$SIGNOZ_PORT/api/v1/dashboards/import"
    
    if [ -n "$SIGNOZ_API_KEY" ]; then
        curl_cmd="$curl_cmd -H \"Authorization: Bearer $SIGNOZ_API_KEY\""
    fi
    
    curl_cmd="$curl_cmd -H \"Content-Type: application/json\" -d @\"$file\""
    
    # Execute import
    local response=$(eval "$curl_cmd")
    
    # Check response
    if echo "$response" | grep -q "success"; then
        echo -e "${GREEN}✓ Successfully imported: $dashboard_name${NC}"
        return 0
    else
        echo -e "${RED}✗ Failed to import: $dashboard_name${NC}"
        echo "Response: $response"
        return 1
    fi
}

# Main import process
echo -e "${YELLOW}=== SigNoz Dashboard Importer for Bakery IA ===${NC}"
echo -e "${BLUE}Configuration:${NC}"
echo "  Host: $SIGNOZ_HOST"
echo "  Port: $SIGNOZ_PORT"
echo "  Dashboards Directory: $DASHBOARDS_DIR"
if [ -n "$SIGNOZ_API_KEY" ]; then
    echo "  API Key: ******** (set)"
else
    echo "  API Key: Not configured"
fi
echo ""

# Count dashboards
DASHBOARD_COUNT=$(find "$DASHBOARDS_DIR" -name "*.json" | wc -l)
echo -e "${BLUE}Found $DASHBOARD_COUNT dashboards to import${NC}"
echo ""

# Import each dashboard
SUCCESS_COUNT=0
FAILURE_COUNT=0

for file in "$DASHBOARDS_DIR"/*.json; do
    if [ -f "$file" ]; then
        # Validate JSON
        if validate_json "$file"; then
            if import_dashboard "$file"; then
                ((SUCCESS_COUNT++))
            else
                ((FAILURE_COUNT++))
            fi
        else
            ((FAILURE_COUNT++))
        fi
        echo ""
    fi
done

# Summary
echo -e "${YELLOW}=== Import Summary ===${NC}"
echo -e "${GREEN}Successfully imported: $SUCCESS_COUNT dashboards${NC}"
if [ $FAILURE_COUNT -gt 0 ]; then
    echo -e "${RED}Failed to import: $FAILURE_COUNT dashboards${NC}"
fi
echo ""

if [ $FAILURE_COUNT -eq 0 ]; then
    echo -e "${GREEN}All dashboards imported successfully!${NC}"
    echo "You can now access them in your SigNoz UI at:"
    echo "http://$SIGNOZ_HOST:$SIGNOZ_PORT/dashboards"
else
    echo -e "${YELLOW}Some dashboards failed to import. Check the errors above.${NC}"
    exit 1
fi