{% extends "admin/base_site.html" %}
{% load static %}

{% block content %}
<div class="px-6 py-4">
    <!-- Page Header -->
    <div class="mb-8 flex justify-between items-center">
        <div>
            <h1 class="text-3xl font-bold text-gray-900 dark:text-white mb-2">AI Cost Analysis</h1>
            <p class="text-gray-600 dark:text-gray-400">Comprehensive cost breakdown with model pricing and predictions</p>
        </div>
        <div>
            <form method="get" class="flex gap-2 items-center">
                <label class="text-sm text-gray-600 dark:text-gray-400">Time Period:</label>
                <select name="days" onchange="this.form.submit()" class="px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
                    <option value="7" {% if days_filter == 7 %}selected{% endif %}>Last 7 Days</option>
                    <option value="30" {% if days_filter == 30 %}selected{% endif %}>Last 30 Days</option>
                    <option value="60" {% if days_filter == 60 %}selected{% endif %}>Last 60 Days</option>
                    <option value="90" {% if days_filter == 90 %}selected{% endif %}>Last 90 Days</option>
                </select>
            </form>
        </div>
    </div>

    <!-- Summary Cards -->
    <div class="grid grid-cols-1 md:grid-cols-6 gap-6 mb-8">
        <div class="bg-gradient-to-br from-blue-500 to-blue-600 rounded-lg shadow-lg p-6 text-white">
            <h3 class="text-sm font-medium opacity-90 mb-2">Total Cost</h3>
            <p class="text-3xl font-bold">${{ total_cost|floatformat:2 }}</p>
            <p class="text-xs opacity-75 mt-1">{{ total_calls }} API calls</p>
        </div>
        <div class="bg-gradient-to-br from-green-500 to-green-600 rounded-lg shadow-lg p-6 text-white">
            <h3 class="text-sm font-medium opacity-90 mb-2">Revenue</h3>
            <p class="text-3xl font-bold">${{ total_revenue|floatformat:2 }}</p>
            <p class="text-xs opacity-75 mt-1">{{ total_credits_charged }} credits @ ${{ credit_price }}</p>
        </div>
        <div class="bg-gradient-to-br from-purple-500 to-purple-600 rounded-lg shadow-lg p-6 text-white">
            <h3 class="text-sm font-medium opacity-90 mb-2">Margin</h3>
            <p class="text-3xl font-bold">${{ total_margin|floatformat:2 }}</p>
            <p class="text-xs opacity-75 mt-1">{{ margin_percentage }}% margin</p>
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <h3 class="text-sm font-medium text-gray-500 dark:text-gray-400 mb-2">Margin / 1M Tokens</h3>
            {% if total_tokens > 0 %}
            <p class="text-3xl font-bold text-purple-600 dark:text-purple-400">${{ margin_per_1m_tokens|floatformat:2 }}</p>
            {% else %}
            <p class="text-xl text-gray-400 dark:text-gray-500">No token data yet</p>
            <p class="text-xs text-gray-500 mt-1">New AI calls will populate this</p>
            {% endif %}
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <h3 class="text-sm font-medium text-gray-500 dark:text-gray-400 mb-2">Margin / 1K Credits</h3>
            {% if total_credits_charged > 0 %}
            <p class="text-3xl font-bold text-green-600 dark:text-green-400">${{ margin_per_1k_credits|floatformat:2 }}</p>
            {% else %}
            <p class="text-xl text-gray-400 dark:text-gray-500">No data</p>
            {% endif %}
        </div>
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <h3 class="text-sm font-medium text-gray-500 dark:text-gray-400 mb-2">Projected Monthly</h3>
            <p class="text-3xl font-bold text-blue-600 dark:text-blue-400">${{ projected_monthly|floatformat:2 }}</p>
            <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">Based on last 7 days</p>
        </div>
    </div>

    <!-- Cost Trends Chart -->
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-8">
        <h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-4">Daily Cost & Volume Trends</h2>
        <canvas id="costTrendsChart" height="80"></canvas>
    </div>

    <!-- Model Comparison Matrix -->
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6 mb-8">
        <h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-4">Model Cost Comparison & Efficiency</h2>
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                <thead>
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Model</th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Total Cost</th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Revenue</th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Margin</th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Margin %</th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">API Calls</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Total Tokens
                            <span class="ml-1 text-xs text-gray-400" title="Token data available for new AI calls after system upgrade">ⓘ</span>
                        </th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Cost/1K Tokens</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                    {% for model in cost_by_model %}
                    <tr class="hover:bg-gray-50 dark:hover:bg-gray-700">
                        <td class="px-6 py-4 text-sm font-medium text-gray-900 dark:text-white">
                            <span class="px-2 py-1 bg-blue-100 dark:bg-blue-900 text-blue-800 dark:text-blue-200 rounded">
                                {{ model.model|default:"Unknown" }}
                            </span>
                        </td>
                        <td class="px-6 py-4 text-sm text-right font-semibold text-red-600 dark:text-red-400">
                            ${{ model.total_cost|floatformat:2 }}
                        </td>
                        <td class="px-6 py-4 text-sm text-right font-semibold text-blue-600 dark:text-blue-400">
                            ${{ model.revenue|floatformat:2 }}
                        </td>
                        <td class="px-6 py-4 text-sm text-right font-semibold text-green-600 dark:text-green-400">
                            ${{ model.margin|floatformat:2 }}
                        </td>
                        <td class="px-6 py-4 text-sm text-right">
                            <span class="px-2 py-1 rounded {% if model.margin_percentage >= 50 %}bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200{% elif model.margin_percentage >= 30 %}bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200{% else %}bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200{% endif %}">
                                {{ model.margin_percentage|floatformat:1 }}%
                            </span>
                        </td>
                        <td class="px-6 py-4 text-sm text-right text-gray-600 dark:text-gray-400">
                            {{ model.call_count }}
                        </td>
                        <td class="px-6 py-4 text-sm text-right text-gray-600 dark:text-gray-400">
                            {{ model.total_tokens|floatformat:0 }}
                        </td>
                        <td class="px-6 py-4 text-sm text-right text-gray-900 dark:text-white">
                            ${{ model.cost_per_1k_tokens|floatformat:4 }}
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>

    <!-- Two Column Layout -->
    <div class="grid grid-cols-1 lg:grid-cols-2 gap-8 mb-8">
        <!-- Cost by Account -->
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-4">Top Spenders (By Account)</h2>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                    <thead>
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Account</th>
                            <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Cost</th>
                            <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Calls</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                        {% for account in cost_by_account %}
                        <tr>
                            <td class="px-4 py-3 text-sm font-medium text-gray-900 dark:text-white">
                                <a href="/admin/igny8_core_auth/account/{{ account.account_id }}/" class="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300">
                                    {{ account.account__name|default:"Unknown" }}
                                </a>
                            </td>
                            <td class="px-4 py-3 text-sm text-right font-semibold text-gray-900 dark:text-white">
                                ${{ account.total_cost|floatformat:2 }}
                            </td>
                            <td class="px-4 py-3 text-sm text-right text-gray-600 dark:text-gray-400">
                                {{ account.call_count }}
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Cost by Function -->
        <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
            <h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-4">Cost by Function/Operation</h2>
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                    <thead>
                        <tr>
                            <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Function</th>
                            <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Cost</th>
                            <th class="px-4 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Calls</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                        {% for func in cost_by_function %}
                        <tr>
                            <td class="px-4 py-3 text-sm font-medium text-gray-900 dark:text-white">
                                {{ func.function|default:"Unknown" }}
                            </td>
                            <td class="px-4 py-3 text-sm text-right font-semibold text-gray-900 dark:text-white">
                                ${{ func.total_cost|floatformat:2 }}
                            </td>
                            <td class="px-4 py-3 text-sm text-right text-gray-600 dark:text-gray-400">
                                {{ func.call_count }}
                            </td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Cost Anomalies -->
    {% if anomalies %}
    <div class="bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 rounded-lg shadow p-6 mb-8">
        <div class="flex items-start">
            <div class="flex-shrink-0">
                <svg class="h-6 w-6 text-amber-600 dark:text-amber-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                </svg>
            </div>
            <div class="ml-3 flex-1">
                <h3 class="text-lg font-semibold text-amber-800 dark:text-amber-200 mb-3">Cost Anomalies Detected</h3>
                <p class="text-sm text-amber-700 dark:text-amber-300 mb-4">The following API calls had unusually high costs (>3x average):</p>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-amber-200 dark:divide-amber-800">
                        <thead>
                            <tr>
                                <th class="px-4 py-2 text-left text-xs font-medium text-amber-700 dark:text-amber-300 uppercase">Model</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-amber-700 dark:text-amber-300 uppercase">Function</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-amber-700 dark:text-amber-300 uppercase">Account</th>
                                <th class="px-4 py-2 text-right text-xs font-medium text-amber-700 dark:text-amber-300 uppercase">Cost</th>
                                <th class="px-4 py-2 text-right text-xs font-medium text-amber-700 dark:text-amber-300 uppercase">Tokens</th>
                                <th class="px-4 py-2 text-left text-xs font-medium text-amber-700 dark:text-amber-300 uppercase">Date</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-amber-200 dark:divide-amber-800">
                            {% for anomaly in anomalies %}
                            <tr>
                                <td class="px-4 py-2 text-sm text-amber-900 dark:text-amber-100">{{ anomaly.model }}</td>
                                <td class="px-4 py-2 text-sm text-amber-900 dark:text-amber-100">{{ anomaly.function }}</td>
                                <td class="px-4 py-2 text-sm text-amber-900 dark:text-amber-100">{{ anomaly.account__name }}</td>
                                <td class="px-4 py-2 text-sm text-right font-bold text-amber-900 dark:text-amber-100">${{ anomaly.cost|floatformat:2 }}</td>
                                <td class="px-4 py-2 text-sm text-right text-amber-800 dark:text-amber-200">{{ anomaly.tokens|floatformat:0 }}</td>
                                <td class="px-4 py-2 text-sm text-amber-800 dark:text-amber-200">{{ anomaly.created_at|date:"M d, H:i" }}</td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    {% endif %}

    <!-- Hourly Cost Distribution -->
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
        <h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-4">Peak Cost Hours</h2>
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
                <thead>
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Hour of Day</th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Total Cost</th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">API Calls</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase">Activity Level</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200 dark:divide-gray-700">
                    {% for hour in hourly_cost %}
                    <tr>
                        <td class="px-6 py-4 text-sm font-medium text-gray-900 dark:text-white">
                            {{ hour.hour|floatformat:0 }}:00 - {{ hour.hour|add:1|floatformat:0 }}:00
                        </td>
                        <td class="px-6 py-4 text-sm text-right text-gray-900 dark:text-white">
                            ${{ hour.total_cost|floatformat:2 }}
                        </td>
                        <td class="px-6 py-4 text-sm text-right text-gray-600 dark:text-gray-400">
                            {{ hour.call_count }}
                        </td>
                        <td class="px-6 py-4 text-sm">
                            <div class="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                                {% widthratio hour.total_cost total_cost 100 as percentage %}
                                <div class="bg-gradient-to-r from-blue-500 to-purple-600 h-2 rounded-full" style="width: {% if percentage > 100 %}100{% else %}{{ percentage }}{% endif %}%"></div>
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
    // Cost & Volume Trends Chart
    const ctx = document.getElementById('costTrendsChart').getContext('2d');
    new Chart(ctx, {
        type: 'line',
        data: {
            labels: {{ daily_cost_labels|safe }},
            datasets: [
                {
                    label: 'Daily Cost ($)',
                    data: {{ daily_cost_data|safe }},
                    borderColor: 'rgb(59, 130, 246)',
                    backgroundColor: 'rgba(59, 130, 246, 0.1)',
                    tension: 0.4,
                    fill: true,
                    yAxisID: 'y'
                },
                {
                    label: 'API Calls',
                    data: {{ daily_call_data|safe }},
                    borderColor: 'rgb(168, 85, 247)',
                    backgroundColor: 'rgba(168, 85, 247, 0.1)',
                    tension: 0.4,
                    fill: true,
                    yAxisID: 'y1'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: true,
            interaction: {
                mode: 'index',
                intersect: false
            },
            plugins: {
                legend: {
                    display: true,
                    position: 'top'
                },
                tooltip: {
                    callbacks: {
                        label: function(context) {
                            let label = context.dataset.label || '';
                            if (label) {
                                label += ': ';
                            }
                            if (context.datasetIndex === 0) {
                                label += '$' + context.parsed.y.toFixed(2);
                            } else {
                                label += context.parsed.y;
                            }
                            return label;
                        }
                    }
                }
            },
            scales: {
                y: {
                    type: 'linear',
                    display: true,
                    position: 'left',
                    title: {
                        display: true,
                        text: 'Cost ($)'
                    },
                    ticks: {
                        callback: function(value) {
                            return '$' + value.toFixed(2);
                        }
                    }
                },
                y1: {
                    type: 'linear',
                    display: true,
                    position: 'right',
                    title: {
                        display: true,
                        text: 'API Calls'
                    },
                    grid: {
                        drawOnChartArea: false
                    }
                }
            }
        }
    });
</script>
{% endblock %}
