#!/bin/bash

# Dubai Analytics Platform - API User Setup Script
# This script helps you register a new user and get your API key

set -e

BASE_URL="http://localhost:8000/api/v1"

echo "🏢 Dubai Analytics Platform - API Setup"
echo "========================================"
echo ""

# Check if curl is installed
if ! command -v curl &> /dev/null; then
    echo "❌ Error: curl is not installed. Please install curl first."
    exit 1
fi

# Check if jq is installed
if ! command -v jq &> /dev/null; then
    echo "⚠️  Warning: jq is not installed. JSON responses will not be formatted."
    echo "   Install jq for better output formatting: sudo apt-get install jq"
    echo ""
fi

# Function to format JSON output
format_json() {
    if command -v jq &> /dev/null; then
        jq '.'
    else
        cat
    fi
}

# Function to register a new user
register_user() {
    echo "📝 User Registration"
    echo "-------------------"
    
    read -p "Enter username: " username
    read -p "Enter email: " email
    read -s -p "Enter password: " password
    echo ""
    read -p "Enter first name: " first_name
    read -p "Enter last name: " last_name
    read -p "Enter company name: " company_name
    
    echo ""
    echo "🔄 Registering user..."
    
    response=$(curl -s -X POST "$BASE_URL/auth/register/" \
        -H "Content-Type: application/json" \
        -d "{
            \"username\": \"$username\",
            \"email\": \"$email\",
            \"password\": \"$password\",
            \"first_name\": \"$first_name\",
            \"last_name\": \"$last_name\",
            \"company_name\": \"$company_name\"
        }")
    
    if echo "$response" | format_json | grep -q "User created successfully"; then
        echo "✅ User registered successfully!"
        echo ""
        
        # Extract API key from response
        api_key=$(echo "$response" | grep -o '"api_key":"[^"]*"' | cut -d'"' -f4)
        
        if [ -n "$api_key" ]; then
            echo "🔑 Your API Key: $api_key"
            echo ""
            echo "📋 Save this API key securely! You'll need it for all API requests."
            echo ""
            echo "🧪 Test your API key:"
            echo "curl -X GET \"$BASE_URL/analytics/broker-stats/\" \\"
            echo "  -H \"X-API-Key: $api_key\""
            echo ""
        else
            echo "❌ Error: Could not extract API key from response"
            echo "Response: $response"
        fi
        
        # Extract JWT token for additional testing
        access_token=$(echo "$response" | grep -o '"access":"[^"]*"' | cut -d'"' -f4)
        
        if [ -n "$access_token" ]; then
            echo "🔐 Your JWT Token (for web interface): $access_token"
            echo ""
        fi
        
    else
        echo "❌ Registration failed!"
        echo "Response: $response" | format_json
        exit 1
    fi
}

# Function to test API key
test_api_key() {
    echo "🧪 API Key Testing"
    echo "-----------------"
    
    read -p "Enter your API key: " api_key
    
    if [ -z "$api_key" ]; then
        echo "❌ API key cannot be empty"
        return 1
    fi
    
    echo "🔄 Testing API key with broker statistics endpoint..."
    
    response=$(curl -s -X GET "$BASE_URL/analytics/broker-stats/" \
        -H "X-API-Key: $api_key")
    
    if echo "$response" | grep -q "gender_distribution"; then
        echo "✅ API key is working correctly!"
        echo ""
        echo "📊 Sample response:"
        echo "$response" | format_json
        echo ""
    else
        echo "❌ API key test failed!"
        echo "Response: $response" | format_json
        echo ""
        echo "Common issues:"
        echo "- Make sure the API key is correct"
        echo "- Make sure the server is running on $BASE_URL"
        echo "- Check if your account has API access enabled"
    fi
}

# Function to show API examples
show_examples() {
    echo "📚 API Usage Examples"
    echo "-------------------"
    echo ""
    
    read -p "Enter your API key: " api_key
    
    if [ -z "$api_key" ]; then
        echo "❌ API key cannot be empty"
        return 1
    fi
    
    echo "🔗 Here are some example API calls you can make:"
    echo ""
    
    echo "1. Get Broker Statistics:"
    echo "curl -X GET \"$BASE_URL/analytics/broker-stats/\" \\"
    echo "  -H \"X-API-Key: $api_key\""
    echo ""
    
    echo "2. Get Project Statistics:"
    echo "curl -X GET \"$BASE_URL/analytics/project-stats/\" \\"
    echo "  -H \"X-API-Key: $api_key\""
    echo ""
    
    echo "3. Get Time Series Data (2025):"
    echo "curl -X GET \"$BASE_URL/analytics/time-series-data/?start_date=2025-01-01&end_date=2025-12-31&group_by=month\" \\"
    echo "  -H \"X-API-Key: $api_key\""
    echo ""
    
    echo "4. Get Transaction Summary:"
    echo "curl -X GET \"$BASE_URL/analytics/transaction-summary/?start_date=2025-01-01&end_date=2025-12-31\" \\"
    echo "  -H \"X-API-Key: $api_key\""
    echo ""
    
    echo "5. Get Area Statistics:"
    echo "curl -X GET \"$BASE_URL/analytics/area-statistics/?start_date=2025-01-01&end_date=2025-12-31&limit=10\" \\"
    echo "  -H \"X-API-Key: $api_key\""
    echo ""
}

# Main menu
while true; do
    echo "What would you like to do?"
    echo "1. Register a new user and get API key"
    echo "2. Test existing API key"
    echo "3. Show API usage examples"
    echo "4. Exit"
    echo ""
    read -p "Enter your choice (1-4): " choice
    
    case $choice in
        1)
            register_user
            ;;
        2)
            test_api_key
            ;;
        3)
            show_examples
            ;;
        4)
            echo "👋 Goodbye!"
            exit 0
            ;;
        *)
            echo "❌ Invalid choice. Please enter 1, 2, 3, or 4."
            ;;
    esac
    
    echo ""
    echo "Press Enter to continue..."
    read
    echo ""
done
