#!/usr/bin/env python3
import cgi, sys
sys.path.insert(0, '/opt/ngon/apps')
from managers.auth_manager import AuthManager, generate_login_page_html

_form = cgi.FieldStorage()
_auth = AuthManager('performance')
_auth_required, _should_exit, _headers = _auth.require_auth(_form)

if _should_exit:
    print("Content-Type: application/json")
    if _headers:
        print(_headers)
    print("")
    if _auth_required:
        print('{"success": false, "error": "Authentication required"}')
    else:
        print('{"success": true}')
    sys.exit(0)

if _auth_required:
    print("Content-Type: text/html")
    print("")
    print(generate_login_page_html("Performance"))
    sys.exit(0)


import json
import sys
import os

# Import the performance data functions directly
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from performance_data_cgi import get_performance_data

# Generate HTML content with dynamic timeframe selection  
def print_html():
    # Import here to avoid circular dependency
    import sys
    import os
    sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    from links import generate_header_html, generate_dropdown_css, generate_dropdown_js, generate_dropdown_html

    print("Content-Type: text/html\n")
    
    # Generate header with time range controls
    additional_controls = '''
        <div class="header-controls">
            <div class="control-group">
                <label class="control-label">Time Range</label>
                <div style="display: flex; gap: 10px;">
                    <button id="btn7" onclick="loadData(7)" class="active">7 Days</button>
                    <button id="btn30" onclick="loadData(30)">30 Days</button>
                    <button id="btn90" onclick="loadData(90)">90 Days</button>
                </div>
            </div>
        </div>
    '''
    
    # Generate header HTML manually to include description
    header_html = f'''
    <div class="header">
        <div>
            <div class="dropdown">
                <h1 class="dropdown-title">NGON Mining - Performance</h1>
                <div class="dropdown-content">{generate_dropdown_html(AuthManager.get_user_access())}</div>
            </div>
            <p style="color: #888; font-size: 14px; margin: 6px 0 0 0;">Historical hashrate analysis and site performance metrics</p>
        </div>
        {additional_controls}
    </div>
    '''
    
    html_content = """
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Performance Monitoring - NGON</title>
        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
        <style>
            * { margin: 0; padding: 0; box-sizing: border-box; }
            """ + generate_dropdown_css() + """
            body { 
                font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
                background: #1a1a1a; 
                color: #ffffff; 
                min-height: 100vh; 
                padding: 20px; 
            }
            .container { max-width: none; margin: 0 auto; }
            
            .header {
                background-color: rgba(255,255,255,0.05) !important;
                border-radius: 8px !important;
                padding: 30px !important;
                margin-bottom: 30px;
                border: 1px solid rgba(255,255,255,0.1) !important;
                border-bottom: none !important;
                display: flex !important;
                justify-content: space-between !important;
                align-items: flex-start !important;
                flex-wrap: wrap;
                gap: 20px;
            }

            .header h1.dropdown-title {
                font-size: 2.2em !important;
                font-weight: 600 !important;
                margin: 3px 0 0 0 !important;
                line-height: 1.2 !important;
                color: #00ff00 !important;
            }
            
            .header-controls {
                display: flex;
                gap: 15px;
                align-items: center;
                flex-wrap: wrap;
            }
            
            .control-group {
                display: flex;
                flex-direction: column;
                gap: 5px;
            }
            
            .control-label {
                color: #ccc;
                font-size: 0.9rem;
                font-weight: 500;
            }
            
            button {
                padding: 10px 15px;
                border: 1px solid rgba(255,255,255,0.2);
                border-radius: 4px;
                background: #2a2a2a;
                color: #ffffff;
                font-size: 0.9rem;
                cursor: pointer;
                transition: all 0.3s ease;
            }
            
            button:hover {
                background: #3a3a3a;
                border-color: #00ff00;
                transform: translateY(-1px);
            }
            
            button.active {
                background: #00ff00;
                color: #000;
                border-color: #00ff00;
            }
            
            .chart-section {
                background-color: rgba(255,255,255,0.05);
                border-radius: 8px;
                padding: 25px;
                margin-bottom: 25px;
                border: 1px solid rgba(255,255,255,0.1);
            }
            
            .chart-title {
                color: #00ff00;
                font-size: 1.4em;
                margin-bottom: 20px;
                font-weight: 600;
            }
            
            .chart-container {
                position: relative;
                height: 400px;
            }
            
            .chart-container.small {
                height: 80px;
            }
            
            .grid-container {
                display: flex;
                flex-wrap: wrap;
                gap: 15px;
                justify-content: center;
            }
            
            .site-card {
                background: #2a2a2a;
                border: 1px solid #3a3a3a;
                border-radius: 8px;
                padding: 15px;
                text-align: center;
                min-width: 150px;
            }
            
            .loading {
                display: inline-block;
                width: 20px;
                height: 20px;
                border: 2px solid #3a3a3a;
                border-radius: 50%;
                border-top-color: #00ff00;
                animation: spin 1s ease-in-out infinite;
                margin-right: 10px;
            }
            
            @keyframes spin {
                to { transform: rotate(360deg); }
            }
            
            .loading-container {
                text-align: center;
                margin: 20px 0;
                display: none;
                color: #888;
                font-size: 16px;
            }
            .summary-table {
                width: 100%;
                border-collapse: collapse;
            }
            .summary-table th {
                color: #888;
                font-size: 0.85rem;
                text-transform: uppercase;
                padding: 10px 12px;
                border-bottom: 1px solid #3a3a3a;
                text-align: right;
            }
            .summary-table th:first-child {
                text-align: left;
            }
            .summary-table td {
                padding: 10px 12px;
                border-bottom: 1px solid rgba(255,255,255,0.05);
                text-align: right;
                font-size: 0.95rem;
            }
            .summary-table td:first-child {
                text-align: left;
            }
            .summary-table tr:hover {
                background: rgba(255,255,255,0.03);
            }
            .summary-select {
                padding: 8px 12px;
                border: 1px solid rgba(255,255,255,0.2);
                border-radius: 4px;
                background: #2a2a2a;
                color: #ffffff;
                font-size: 0.9rem;
                cursor: pointer;
            }
            .summary-select:hover {
                border-color: #00ff00;
            }
        </style>
    </head>
    <body>
        <div class="container">
            """ + header_html + """

            <!-- Loading indicator -->
            <div id="loadingIndicator" class="loading-container">
                <div class="loading"></div>
                Loading performance data...
            </div>

            <!-- Current Hashrate Bar Chart -->
            <div class="chart-section">
                <h3 class="chart-title">Current Hashrate</h3>
                <div class="chart-container small">
                    <canvas id="totalHashrateBar"></canvas>
                </div>
                <div style="text-align: center; margin-top: 15px; color: #888;">
                    Current vs Maximum Capacity
                </div>
            </div>

            <!-- Total Hashrate History Chart -->
            <div class="chart-section">
                <h3 id="totalHistoryTitle" class="chart-title">Total Hashrate History (7 Days)</h3>
                <div class="chart-container">
                    <canvas id="totalHashrateLineChart"></canvas>
                </div>
            </div>

            <!-- Site Hashrate History Chart -->
            <div class="chart-section">
                <h3 id="siteHistoryTitle" class="chart-title">Site Hashrate History (7 Days)</h3>
                <div class="chart-container">
                    <canvas id="containerLineChart"></canvas>
                </div>
            </div>

            <!-- Current Site Hashrates Grid -->
            <div class="chart-section">
                <h3 class="chart-title">Current Site Hashrates</h3>
                <div id="containerHashrateList" class="grid-container"></div>
            </div>

            <!-- Regional Pool Hashrates (post-2026-08-01 two-worker cutover) -->
            <div class="chart-section">
                <h3 class="chart-title">Current Pool Hashrates</h3>
                <div id="poolHashrateList" class="grid-container"></div>
            </div>

            <!-- Site Hashrate Summary -->
            <div class="chart-section">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; flex-wrap: wrap; gap: 10px;">
                    <h3 class="chart-title" style="margin-bottom: 0;">Site Hashrate Summary</h3>
                    <div style="display: flex; gap: 10px; align-items: center;">
                        <label style="color: #888; font-size: 0.9rem;">Period:</label>
                        <select id="summaryPeriod" onchange="loadSummaryData()" class="summary-select">
                            <option value="1">24 Hours</option>
                            <option value="7">7 Days</option>
                            <option value="14">14 Days</option>
                            <option value="30" selected>30 Days</option>
                            <option value="90">90 Days</option>
                            <option value="3650">All Time</option>
                        </select>
                    </div>
                </div>
                <div id="summaryLoading" style="text-align: center; color: #888; padding: 20px; display: none;">
                    <div class="loading" style="display: inline-block; vertical-align: middle;"></div>
                    Loading summary data...
                </div>
                <table id="summaryTable" class="summary-table" style="display: none;">
                    <thead>
                        <tr>
                            <th>Site</th>
                            <th>Nameplate (PH/s)</th>
                            <th>Expected (PH/s)</th>
                            <th>Avg Actual (PH/s)</th>
                            <th>% of Nameplate</th>
                            <th>% of Expected</th>
                        </tr>
                    </thead>
                    <tbody id="summaryTableBody"></tbody>
                </table>
                <p id="summaryFootnote" style="display: none; color: #888; font-size: 0.85rem; margin-top: 15px;">Assumed working rates for expected hashrate (ie after failure rates): M60, 95%; S19JPro, 88%; XP, 60%</p>
            </div>
        </div>

        <script>
            // Chart instances to manage destruction/recreation
            let chartInstances = {
                barChart: null,
                totalLineChart: null,
                siteLineChart: null
            };

            // Current data storage
            let currentData = null;

            // Function to format ISO time strings for display
            function formatDate(isoString, days) {
                const date = new Date(isoString);
                if (days <= 7) {
                    // For 7 days, show date and time
                    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) + 
                           ' ' + date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' });
                } else {
                    // For longer periods, just show date
                    return date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' });
                }
            }

            // Update button styles
            function updateButtonStyles(activeDays) {
                const buttons = ['btn7', 'btn30', 'btn90'];
                buttons.forEach(btnId => {
                    const btn = document.getElementById(btnId);
                    const days = parseInt(btnId.replace('btn', ''));
                    if (days === activeDays) {
                        btn.classList.add('active');
                        btn.classList.remove('inactive');
                    } else {
                        btn.classList.remove('active');
                        btn.classList.add('inactive');
                    }
                });
            }

            // Load data from API
            async function loadData(days) {
                console.log(`Loading ${days} days of data...`);
                
                // Update button styles
                updateButtonStyles(days);
                
                // Show loading indicator
                document.getElementById('loadingIndicator').style.display = 'block';

                try {
                    // Determine aggregation based on days
                    let aggregation = '1h'; // Default hourly
                    if (days >= 30) {
                        aggregation = '1d'; // Daily for 30+ days
                    }

                    const response = await fetch(`performance_data_cgi.py?days=${days}&aggregation=${aggregation}`);
                    const apiResponse = await response.json();
                    
                    if (!apiResponse.success) {
                        throw new Error(apiResponse.error || 'Failed to load data');
                    }
                    
                    currentData = apiResponse.data;
                    
                    // Update titles
                    document.getElementById('totalHistoryTitle').textContent = `Total Hashrate History (${days} Days)`;
                    document.getElementById('siteHistoryTitle').textContent = `Site Hashrate History (${days} Days)`;
                    
                    // Clear and regenerate all charts and data
                    clearSiteGrid();
                    destroyCharts();
                    createBarChart();
                    populateSiteGrid();
                    createTotalLineChart(days);
                    createSiteLineChart(days);
                    
                } catch (error) {
                    console.error('Error loading data:', error);
                    alert(`Error loading data: ${error.message}`);
                } finally {
                    // Hide loading indicator
                    document.getElementById('loadingIndicator').style.display = 'none';
                }
            }

            // Destroy existing chart instances
            function destroyCharts() {
                Object.values(chartInstances).forEach(chart => {
                    if (chart) chart.destroy();
                });
                chartInstances = {
                    barChart: null,
                    totalLineChart: null,
                    siteLineChart: null
                };
            }

            // Clear site grid
            function clearSiteGrid() {
                const containerList = document.getElementById('containerHashrateList');
                containerList.innerHTML = '';
                document.getElementById('poolHashrateList').innerHTML = '';
            }

            // Create bar chart
            function createBarChart() {
                const ctx = document.getElementById('totalHashrateBar').getContext('2d');
                const totalHashrateCurrent = currentData.total_hashrate_current;
                const maxPH = currentData.max_ph;
                const unfilledPH = Math.max(0, maxPH - totalHashrateCurrent);
                
                chartInstances.barChart = new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: ['Current Hashrate'],
                        datasets: [
                            {
                                label: 'Current',
                                data: [totalHashrateCurrent],
                                backgroundColor: ['#00ff00'],
                                borderColor: ['rgba(0, 204, 0, 1)'],
                                borderWidth: 0
                            },
                            {
                                label: 'Available',
                                data: [unfilledPH],
                                backgroundColor: ['#3a3a3a'],
                                borderColor: ['rgba(58, 58, 58, 1)'],
                                borderWidth: 0
                            }
                        ]
                    },
                    options: {
                        indexAxis: 'y',
                        scales: {
                            x: {
                                stacked: true,
                                min: 0,
                                max: maxPH,
                                ticks: { color: '#888' },
                                grid: { color: '#2a2a2a' }
                            },
                            y: {
                                stacked: true,
                                ticks: { color: '#888' },
                                grid: { color: '#2a2a2a' }
                            }
                        },
                        plugins: {
                            legend: { display: false }
                        },
                        maintainAspectRatio: false,
                        responsive: true
                    }
                });
            }

            // Populate site grid. Site cards are ours-only: after the 2026-08-01
            // two-worker cutover the pool only knows ND vs TX, so pool hashrate
            // lives in its own grid below (populatePoolGrid).
            function populateSiteGrid() {
                const containerList = document.getElementById('containerHashrateList');
                const containersHashrateCurrent = currentData.containers_hashrate_current;
                const maxPotentialHashrate = currentData.max_potential_hashrate;

                Object.keys(containersHashrateCurrent).sort().forEach(site => {
                    const hashrate = containersHashrateCurrent[site] || 0;
                    const maxPotential = maxPotentialHashrate[site] || 0;

                    const siteContainer = document.createElement('div');
                    siteContainer.className = 'site-card';
                    siteContainer.innerHTML = `
                        <h4 style="color: #fff; margin-bottom: 8px;">${site}</h4>
                        <div style="color: #888; font-size: 12px; margin-bottom: 5px;">Max: ${maxPotential.toFixed(2)} PH/s</div>
                        <div style="color: #00ff00; font-size: 18px; font-weight: bold;">${hashrate.toFixed(2)} PH/s</div>
                    `;
                    containerList.appendChild(siteContainer);
                });

                populatePoolGrid();
            }

            // Regional pool grid: one card per Foundry regional sub-account (ND / TX)
            // with our own measured hashrate alongside, plus a roll-up of the retired
            // per-site sub-accounts that stubborn miners are still hashing into.
            function populatePoolGrid() {
                const poolList = document.getElementById('poolHashrateList');
                const pool = currentData.pool_regional;
                if (!pool) {
                    poolList.innerHTML = '<div style="color:#888;padding:10px;">Pool data unavailable</div>';
                    return;
                }

                const card = (html, accent) => {
                    const el = document.createElement('div');
                    el.className = 'site-card';
                    el.style.borderLeft = `3px solid ${accent}`;
                    el.style.minWidth = '190px';
                    el.innerHTML = html;
                    return el;
                };

                (pool.regions || []).forEach(region => {
                    const oursPh = region.ours_ph || 0;
                    // Ours-vs-pool gap: the pool is the money number, ours is what our
                    // scans see. A persistent gap means we're under/over-counting.
                    let deltaHtml = '';
                    if (oursPh > 0 && region.ok) {
                        const deltaPct = ((region.ph - oursPh) / oursPh) * 100;
                        const color = Math.abs(deltaPct) > 5 ? '#ffaa00' : '#888';
                        deltaHtml = `<div style="color:${color};font-size:11px;margin-top:3px;">${deltaPct >= 0 ? '+' : ''}${deltaPct.toFixed(1)}% vs ours</div>`;
                    }
                    poolList.appendChild(card(`
                        <h4 style="color:#fff;margin-bottom:8px;">${region.region} Pool</h4>
                        <div style="color:${region.ok ? '#00ff00' : '#ff4444'};font-size:18px;font-weight:bold;">${region.ok ? region.ph.toFixed(2) + ' PH/s' : 'unavailable'}</div>
                        <div style="color:#888;font-size:12px;margin-top:5px;">Ours: ${oursPh.toFixed(2)} PH/s</div>
                        ${deltaHtml}
                        <div style="color:#666;font-size:11px;margin-top:5px;">${region.workers.toLocaleString()} workers${region.offline_15m ? ' &bull; ' + region.offline_15m.toLocaleString() + ' offline' : ''}</div>
                        <div style="color:#555;font-size:10px;margin-top:3px;">${region.name}</div>
                    `, region.ok ? '#00ff00' : '#ff4444'));
                });

                // Stragglers: miners that never took the regional pool config. Should
                // trend to zero — the breakdown says which site to go chase.
                const legacy = pool.legacy || { ph: 0, workers: 0, accounts: [] };
                const hasStragglers = legacy.ph > 0 || legacy.workers > 0;
                const breakdown = (legacy.accounts || []).length
                    ? legacy.accounts.map(a => `${a.label}: ${a.ph.toFixed(2)} PH/s (${a.workers})`).join('<br>')
                    : 'All miners on regional workers';
                poolList.appendChild(card(`
                    <h4 style="color:#fff;margin-bottom:8px;">Other Subaccounts</h4>
                    <div style="color:${hasStragglers ? '#ffaa00' : '#888'};font-size:18px;font-weight:bold;">${legacy.ph.toFixed(2)} PH/s</div>
                    <div style="color:#888;font-size:12px;margin-top:5px;">${legacy.workers.toLocaleString()} workers on old pools</div>
                    <div style="color:#666;font-size:11px;margin-top:5px;line-height:1.5;">${breakdown}</div>
                `, hasStragglers ? '#ffaa00' : '#3a3a3a'));
            }

            // Create total hashrate line chart
            function createTotalLineChart(days) {
                const ctx = document.getElementById('totalHashrateLineChart').getContext('2d');
                const totalHashrateData = currentData.total_hashrate_30d; // API returns data for requested period
                
                const labels = totalHashrateData.map(entry => formatDate(entry.time, days));
                const data = totalHashrateData.map(entry => entry.value);

                chartInstances.totalLineChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: labels,
                        datasets: [{
                            label: 'Total Hashrate',
                            data: data,
                            borderColor: '#00ff00',
                            backgroundColor: 'rgba(0, 255, 0, 0.1)',
                            borderWidth: 1,
                            pointRadius: 2,
                            pointHoverRadius: 4,
                            fill: true,
                            tension: 0.3
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: true,
                                labels: {
                                    usePointStyle: true,
                                    pointStyle: 'line',
                                    color: '#e0e0e0',
                                    font: { size: 14 }
                                }
                            }
                        },
                        scales: {
                            x: {
                                ticks: { 
                                    color: '#888',
                                    maxTicksLimit: days <= 7 ? 12 : 8
                                },
                                grid: { color: '#2a2a2a' }
                            },
                            y: {
                                beginAtZero: true,
                                ticks: { color: '#888' },
                                grid: { color: '#2a2a2a' }
                            }
                        }
                    }
                });
            }

            // Create site hashrate line chart
            function createSiteLineChart(days) {
                const ctx = document.getElementById('containerLineChart').getContext('2d');
                const containersHashrateData = currentData.containers_hashrate_30d; // API returns data for requested period
                
                // Check if we have data
                if (!containersHashrateData || Object.keys(containersHashrateData).length === 0) {
                    ctx.canvas.parentElement.innerHTML = '<p style="text-align: center; color: #888; padding: 50px;">No site data available</p>';
                    return;
                }

                const labels = Object.values(containersHashrateData)[0].map(entry => formatDate(entry.time, days));
                const colors = ['#00ff00', '#4a9eff', '#ff6600', '#ff4444', '#ffaa00', '#aa44ff', '#44ffaa', '#ff44aa'];
                
                const datasets = Object.keys(containersHashrateData).sort().map((site, idx) => {
                    const data = containersHashrateData[site].map(entry => entry.value);
                    const color = colors[idx % colors.length];
                    return {
                        label: site,
                        data: data,
                        fill: true,
                        tension: 0.3,
                        borderColor: color,
                        backgroundColor: color + '20',
                        borderWidth: 1,
                        pointRadius: 2,
                        pointHoverRadius: 4
                    };
                });

                chartInstances.siteLineChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: labels,
                        datasets: datasets
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                display: true,
                                labels: {
                                    usePointStyle: true,
                                    pointStyle: 'line',
                                    color: '#e0e0e0',
                                    font: { size: 14 }
                                }
                            }
                        },
                        scales: {
                            x: {
                                ticks: { 
                                    color: '#888',
                                    maxTicksLimit: days <= 7 ? 12 : 8
                                },
                                grid: { color: '#2a2a2a' }
                            },
                            y: {
                                beginAtZero: true,
                                ticks: { color: '#888' },
                                grid: { color: '#2a2a2a' }
                            }
                        }
                    }
                });
            }

            // Site Hashrate Summary
            async function loadSummaryData() {
                const days = document.getElementById('summaryPeriod').value;
                const loading = document.getElementById('summaryLoading');
                const table = document.getElementById('summaryTable');

                loading.style.display = 'block';
                table.style.display = 'none';

                try {
                    const response = await fetch(`performance_data_cgi.py?mode=summary&days=${days}`);
                    const result = await response.json();
                    if (!result.success) throw new Error(result.error || 'Failed to load summary');

                    const nameplate = result.data.max_potential_hashrate;
                    const expected = result.data.expected_hashrate;
                    const avgActual = result.data.site_avg_hashrate;
                    const tbody = document.getElementById('summaryTableBody');
                    tbody.innerHTML = '';

                    const allSites = new Set([...Object.keys(nameplate), ...Object.keys(avgActual)]);
                    const sorted = [...allSites].sort();

                    let totalNameplate = 0;
                    let totalExpected = 0;
                    let totalActual = 0;

                    sorted.forEach(site => {
                        const np = nameplate[site] || 0;
                        const exp = expected[site] || 0;
                        const actual = avgActual[site] || 0;
                        const pctNp = np > 0 ? (actual / np * 100) : 0;
                        const pctExp = exp > 0 ? (actual / exp * 100) : 0;
                        totalNameplate += np;
                        totalExpected += exp;
                        totalActual += actual;

                        const pctNpColor = pctNp >= 90 ? '#00ff00' : pctNp >= 70 ? '#ffaa00' : '#ff4444';
                        const pctExpColor = pctExp >= 90 ? '#00ff00' : pctExp >= 70 ? '#ffaa00' : '#ff4444';

                        const row = document.createElement('tr');
                        row.innerHTML = `
                            <td style="font-weight: 600; color: #fff;">${site}</td>
                            <td>${np.toFixed(2)}</td>
                            <td>${exp.toFixed(2)}</td>
                            <td>${actual.toFixed(2)}</td>
                            <td style="color: ${pctNpColor}; font-weight: 600;">${pctNp.toFixed(1)}%</td>
                            <td style="color: ${pctExpColor}; font-weight: 600;">${pctExp.toFixed(1)}%</td>
                        `;
                        tbody.appendChild(row);
                    });

                    // Total row
                    const totalPctNp = totalNameplate > 0 ? (totalActual / totalNameplate * 100) : 0;
                    const totalPctExp = totalExpected > 0 ? (totalActual / totalExpected * 100) : 0;
                    const totalPctNpColor = totalPctNp >= 90 ? '#00ff00' : totalPctNp >= 70 ? '#ffaa00' : '#ff4444';
                    const totalPctExpColor = totalPctExp >= 90 ? '#00ff00' : totalPctExp >= 70 ? '#ffaa00' : '#ff4444';
                    const totalRow = document.createElement('tr');
                    totalRow.style.borderTop = '2px solid #00ff00';
                    totalRow.innerHTML = `
                        <td style="font-weight: 700; color: #00ff00;">TOTAL</td>
                        <td style="font-weight: 700;">${totalNameplate.toFixed(2)}</td>
                        <td style="font-weight: 700;">${totalExpected.toFixed(2)}</td>
                        <td style="font-weight: 700;">${totalActual.toFixed(2)}</td>
                        <td style="color: ${totalPctNpColor}; font-weight: 700;">${totalPctNp.toFixed(1)}%</td>
                        <td style="color: ${totalPctExpColor}; font-weight: 700;">${totalPctExp.toFixed(1)}%</td>
                    `;
                    tbody.appendChild(totalRow);

                    loading.style.display = 'none';
                    table.style.display = 'table';
                    document.getElementById('summaryFootnote').style.display = 'block';
                } catch (error) {
                    console.error('Error loading summary:', error);
                    loading.innerHTML = '<span style="color: #ff4444;">Error loading summary data</span>';
                }
            }

            // Initialize page

            // Load initial data (7 days) when page loads
            window.addEventListener('load', () => {
                loadData(7);
                loadSummaryData();
            });
        </script>
        
        <script>
            """ + generate_dropdown_js() + """
        </script>

    </body>
    </html>
    """
    
    print(html_content)

if __name__ == "__main__":
    print_html()


