<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Report</title>
    <style>
        /* CSS styles for the report */
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
            color: #333;
        }
        .header {
            background-color: #2c3e50;
            color: white;
            padding: 20px;
            text-align: center;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        .summary {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
            background-color: white;
            border-radius: 5px;
            padding: 15px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .summary-item {
            text-align: center;
            padding: 10px;
        }
        .summary-item .count {
            font-size: 24px;
            font-weight: bold;
        }
        .summary-item .label {
            font-size: 14px;
            color: #777;
        }
        .pass { color: #27ae60; }
        .fail { color: #e74c3c; }
        .skip { color: #f39c12; }
        .error { color: #c0392b; }
        
        .test-list {
            background-color: white;
            border-radius: 5px;
            padding: 15px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .test-item {
            border-bottom: 1px solid #eee;
            padding: 15px 0;
        }
        .test-item:last-child {
            border-bottom: none;
        }
        .test-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: pointer;
        }
        .test-name {
            font-weight: bold;
        }
        .test-status {
            padding: 5px 10px;
            border-radius: 3px;
            font-size: 12px;
            font-weight: bold;
        }
        .status-pass { background-color: #e8f5e9; color: #27ae60; }
        .status-fail { background-color: #fdecea; color: #e74c3c; }
        .status-skip { background-color: #fff8e1; color: #f39c12; }
        .status-error { background-color: #fbe9e7; color: #c0392b; }
        
        .test-details {
            display: block; /* Show test details by default */
            padding: 10px;
            background-color: #f9f9f9;
            border-radius: 3px;
            margin-top: 10px;
        }
        .test-logs {
            font-family: monospace;
            white-space: pre-wrap;
            background-color: #f5f5f5;
            padding: 10px;
            border-radius: 3px;
            margin-top: 10px;
            max-height: 300px;
            overflow-y: auto;
        }
        .assertion-error {
            background-color: #fef8f8;
            border-left: 4px solid #e74c3c;
            padding: 10px;
            margin-top: 10px;
            font-size: 14px;
            font-family: monospace;
            white-space: pre-wrap;
        }
        .assertion-error strong {
            color: #e74c3c;
            margin-right: 5px;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .assertion-error strong.fail {
            color: #e74c3c;
        }
        .success-message {
            background-color: #e8f5e9;
            border-left: 4px solid #27ae60;
            padding: 10px;
            margin-top: 10px;
            font-size: 14px;
            font-family: monospace;
            white-space: pre-wrap;
        }
        .assertion-error span {
            display: block;
            margin: 2px 0;
        }
        .traceback {
            font-size: 12px;
            color: #555;
            max-height: 200px;
        }
        .environment {
            background-color: white;
            border-radius: 5px;
            padding: 15px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            margin-top: 20px;
        }
        .environment-title {
            font-weight: bold;
            margin-bottom: 10px;
        }
        .environment-item {
            display: flex;
            margin-bottom: 5px;
        }
        .environment-key {
            font-weight: bold;
            width: 150px;
        }
        .charts {
            display: flex;
            justify-content: space-between;
            margin: 20px 0;
        }
        .chart {
            background-color: white;
            border-radius: 5px;
            padding: 15px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            width: 48%;
        }
        .footer {
            text-align: center;
            margin-top: 20px;
            padding: 10px;
            color: #777;
            font-size: 12px;
        }
        .metadata {
            margin-top: 10px;
            padding: 10px;
            background-color: #f0f0f0;
            border-radius: 3px;
        }
        .metadata-item {
            margin-bottom: 5px;
        }
        .metadata-key {
            font-weight: bold;
            display: inline-block;
            width: 100px;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>Test Report</h1>
        <p>{{ results.start_time }}</p>
    </div>
    
    <div class="container">
        <div class="summary">
            <div class="summary-item">
                <div class="count">{{ results.summary.total }}</div>
                <div class="label">TOTAL</div>
            </div>
            <div class="summary-item">
                <div class="count pass">{{ results.summary.passed }}</div>
                <div class="label">PASSED</div>
            </div>
            <div class="summary-item">
                <div class="count fail">{{ results.summary.failed }}</div>
                <div class="label">FAILED</div>
            </div>
            <div class="summary-item">
                <div class="count skip">{{ results.summary.skipped }}</div>
                <div class="label">SKIPPED</div>
            </div>
            <div class="summary-item">
                <div class="count error">{{ results.summary.errors }}</div>
                <div class="label">ERRORS</div>
            </div>
            <div class="summary-item">
                <div class="count">{{ results.duration|floatformat:2 }}s</div>
                <div class="label">DURATION</div>
            </div>
        </div>
        
        <div class="charts">
            <div class="chart">
                <canvas id="statusChart" width="400" height="200"></canvas>
            </div>
            <div class="chart">
                <canvas id="durationChart" width="400" height="200"></canvas>
            </div>
        </div>
        
        <div class="test-list">
            <h2>Test Results</h2>
            {% for test in results.tests %}
            <div class="test-item">
                <div class="test-header">
                    <div class="test-name">{{ test.class }}.{{ test.method }}</div>
                    <div class="test-status status-{{ test.status|lower }}">{{ test.status }}</div>
                </div>
                <div id="test-{{ forloop.counter }}" class="test-details">
                    <div><strong>Duration:</strong> {{ test.duration|floatformat:2 }}s</div>
                    
                    {% if test.metadata %}
                    <div class="metadata">
                        {% if test.metadata.category %}
                        <div class="metadata-item">
                            <span class="metadata-key">Category:</span>
                            <span>{{ test.metadata.category }}</span>
                        </div>
                        {% endif %}
                        
                        {% if test.metadata.author %}
                        <div class="metadata-item">
                            <span class="metadata-key">Author:</span>
                            <span>{{ test.metadata.author }}</span>
                        </div>
                        {% endif %}
                        
                        {% if test.metadata.description %}
                        <div class="metadata-item">
                            <span class="metadata-key">Description:</span>
                            <span>{{ test.metadata.description }}</span>
                        </div>
                        {% endif %}
                    </div>
                    {% endif %}
                    
                    {% if test.assertion_html %}
                    <div>
                        <strong>Assertion Failed:</strong>
                        <div class="test-logs assertion-error">{{ test.assertion_html|safe }}</div>
                    </div>
                    {% endif %}
                    
                    {% if test.success_message and test.status == 'PASS' %}
                    <div>
                        <strong class="pass">Success:</strong>
                        <div class="test-logs success-message">{{ test.success_message }}</div>
                    </div>
                    {% endif %}
                    
                    {% if test.error_message %}
                    <div>
                        <strong>Error Details:</strong>
                        <div class="test-logs">{{ test.error_message }}</div>
                    </div>
                    {% endif %}
                    
                    {% if test.skip_reason %}
                    <div><strong>Skip Reason:</strong> {{ test.skip_reason }}</div>
                    {% endif %}
                    
                    {% if test.logs %}
                    <div>
                        <strong>Logs:</strong>
                        <div class="test-logs">
                            {% for log in test.logs %}
                            {{ log }}<br>
                            {% endfor %}
                        </div>
                    </div>
                    {% endif %}
                </div>
            </div>
            {% endfor %}
        </div>
        
        <div class="environment">
            <div class="environment-title">Environment</div>
            {% for key, value in results.environment.items %}
            <div class="environment-item">
                <div class="environment-key">{{ key|title }}</div>
                <div class="environment-value">{{ value }}</div>
            </div>
            {% endfor %}
        </div>
    </div>
    
    <div class="footer">
        <p>Report generated on {{ results.end_time }}</p>
    </div>
    
    <!-- Load Chart.js with fallback -->
    <script>
        // Function to toggle test details
        function toggleDetails(id) {
            const details = document.getElementById(id);
            if (details) {
                details.style.display = details.style.display === 'none' ? 'block' : 'none';
            }
        }
        
        // Function to load Chart.js from CDN with fallback
        function loadChartJS(callback) {
            // Try to load from CDN
            var script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js';
            script.onload = function() {
                console.log('Chart.js loaded from CDN');
                callback();
            };
            script.onerror = function() {
                console.error('Failed to load Chart.js from CDN, using embedded version');
                // Embedded minimal version of Chart.js (if CDN fails)
                var embeddedScript = document.createElement('script');
                embeddedScript.textContent = `
                // Minimal Chart.js implementation for fallback
                class Chart {
                    constructor(ctx, config) {
                        this.ctx = ctx;
                        this.config = config;
                        this.render();
                    }
                    
                    render() {
                        const canvas = this.ctx.canvas;
                        const ctx = this.ctx;
                        
                        // Clear canvas
                        ctx.clearRect(0, 0, canvas.width, canvas.height);
                        
                        if (this.config.type === 'pie') {
                            this.renderPieChart(ctx, canvas, this.config);
                        } else if (this.config.type === 'bar') {
                            this.renderBarChart(ctx, canvas, this.config);
                        }
                    }
                    
                    renderPieChart(ctx, canvas, config) {
                        const data = config.data.datasets[0].data;
                        const colors = config.data.datasets[0].backgroundColor;
                        const labels = config.data.labels;
                        const total = data.reduce((a, b) => a + b, 0);
                        
                        // Draw title
                        ctx.font = 'bold 14px Arial';
                        ctx.textAlign = 'center';
                        ctx.fillText(config.options.plugins.title.text, canvas.width / 2, 20);
                        
                        // Draw pie
                        let startAngle = 0;
                        const centerX = canvas.width / 2;
                        const centerY = canvas.height / 2;
                        const radius = Math.min(centerX, centerY) - 40;
                        
                        for (let i = 0; i < data.length; i++) {
                            const sliceAngle = 2 * Math.PI * data[i] / total;
                            
                            ctx.beginPath();
                            ctx.moveTo(centerX, centerY);
                            ctx.arc(centerX, centerY, radius, startAngle, startAngle + sliceAngle);
                            ctx.closePath();
                            
                            ctx.fillStyle = colors[i];
                            ctx.fill();
                            
                            startAngle += sliceAngle;
                        }
                        
                        // Draw legend
                        const legendX = canvas.width - 100;
                        let legendY = 50;
                        
                        for (let i = 0; i < labels.length; i++) {
                            ctx.fillStyle = colors[i];
                            ctx.fillRect(legendX, legendY, 15, 15);
                            
                            ctx.fillStyle = '#000';
                            ctx.font = '12px Arial';
                            ctx.textAlign = 'left';
                            ctx.fillText(labels[i] + ': ' + data[i], legendX + 20, legendY + 12);
                            
                            legendY += 25;
                        }
                    }
                    
                    renderBarChart(ctx, canvas, config) {
                        const data = config.data.datasets[0].data;
                        const labels = config.data.labels;
                        const colors = config.data.datasets[0].backgroundColor;
                        
                        // Draw title
                        ctx.font = 'bold 14px Arial';
                        ctx.textAlign = 'center';
                        ctx.fillText(config.options.plugins.title.text, canvas.width / 2, 20);
                        
                        // Find max value for scaling
                        const maxValue = Math.max(...data);
                        const barWidth = (canvas.width - 100) / data.length;
                        const barHeightScale = (canvas.height - 80) / maxValue;
                        
                        // Draw bars
                        for (let i = 0; i < data.length; i++) {
                            const barHeight = data[i] * barHeightScale;
                            const x = 50 + i * barWidth;
                            const y = canvas.height - 40 - barHeight;
                            
                            ctx.fillStyle = Array.isArray(colors) ? colors[i] : colors;
                            ctx.fillRect(x, y, barWidth - 5, barHeight);
                            
                            // Draw label
                            ctx.fillStyle = '#000';
                            ctx.font = '10px Arial';
                            ctx.textAlign = 'center';
                            ctx.fillText(labels[i].substring(0, 8) + '...', x + barWidth / 2, canvas.height - 25);
                        }
                        
                        // Draw y-axis
                        ctx.beginPath();
                        ctx.moveTo(50, 40);
                        ctx.lineTo(50, canvas.height - 40);
                        ctx.stroke();
                        
                        // Draw x-axis
                        ctx.beginPath();
                        ctx.moveTo(50, canvas.height - 40);
                        ctx.lineTo(canvas.width - 50, canvas.height - 40);
                        ctx.stroke();
                    }
                }`;
                document.head.appendChild(embeddedScript);
                callback();
            };
            document.head.appendChild(script);
        }
        
        // Initialize charts when DOM is loaded
        document.addEventListener('DOMContentLoaded', function() {
            console.log('DOM loaded, initializing charts');
            loadChartJS(function() {
                try {
                    initializeCharts();
                } catch (error) {
                    console.error('Error initializing charts:', error);
                    document.getElementById('statusChart').insertAdjacentHTML('afterend', 
                        '<div style="color: red; text-align: center;">Error loading chart: ' + error.message + '</div>');
                    document.getElementById('durationChart').insertAdjacentHTML('afterend', 
                        '<div style="color: red; text-align: center;">Error loading chart: ' + error.message + '</div>');
                }
            });
        });
        
        // Function to initialize charts
        function initializeCharts() {
            console.log('Initializing charts');
            
            // Status chart
            try {
                const statusCtx = document.getElementById('statusChart').getContext('2d');
                console.log('Status chart canvas:', statusCtx ? 'found' : 'not found');
                
                if (!statusCtx) {
                    throw new Error('Status chart canvas not found');
                }
                
                const statusData = [
                    {{ results.summary.passed }}, 
                    {{ results.summary.failed }}, 
                    {{ results.summary.skipped }}, 
                    {{ results.summary.errors }}
                ];
                console.log('Status data:', statusData);
                
                const statusChart = new Chart(statusCtx, {
                    type: 'pie',
                    data: {
                        labels: ['Passed', 'Failed', 'Skipped', 'Errors'],
                        datasets: [{
                            data: statusData,
                            backgroundColor: [
                                '#27ae60',
                                '#e74c3c',
                                '#f39c12',
                                '#c0392b'
                            ]
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: {
                            legend: {
                                position: 'right',
                            },
                            title: {
                                display: true,
                                text: 'Test Status Distribution'
                            }
                        }
                    }
                });
                console.log('Status chart created');
            } catch (error) {
                console.error('Error creating status chart:', error);
                document.getElementById('statusChart').insertAdjacentHTML('afterend', 
                    '<div style="color: red; text-align: center;">Error creating status chart: ' + error.message + '</div>');
            }
            
            // Duration chart
            try {
                const durationCtx = document.getElementById('durationChart').getContext('2d');
                console.log('Duration chart canvas:', durationCtx ? 'found' : 'not found');
                
                if (!durationCtx) {
                    throw new Error('Duration chart canvas not found');
                }
                
                const durationLabels = [{% for test in results.tests %}'{{ test.method }}',{% endfor %}];
                const durationData = [{% for test in results.tests %}{{ test.duration|floatformat:2 }},{% endfor %}];
                const backgroundColors = [{% for test in results.tests %}
                    {% if test.status == 'PASS' %}'rgba(39, 174, 96, 0.2)'{% endif %}
                    {% if test.status == 'FAIL' %}'rgba(231, 76, 60, 0.2)'{% endif %}
                    {% if test.status == 'SKIP' %}'rgba(243, 156, 18, 0.2)'{% endif %}
                    {% if test.status == 'ERROR' %}'rgba(192, 57, 43, 0.2)'{% endif %},
                {% endfor %}];
                const borderColors = [{% for test in results.tests %}
                    {% if test.status == 'PASS' %}'rgba(39, 174, 96, 1)'{% endif %}
                    {% if test.status == 'FAIL' %}'rgba(231, 76, 60, 1)'{% endif %}
                    {% if test.status == 'SKIP' %}'rgba(243, 156, 18, 1)'{% endif %}
                    {% if test.status == 'ERROR' %}'rgba(192, 57, 43, 1)'{% endif %},
                {% endfor %}];
                
                console.log('Duration data:', durationData);
                
                const durationChart = new Chart(durationCtx, {
                    type: 'bar',
                    data: {
                        labels: durationLabels,
                        datasets: [{
                            label: 'Test Duration (seconds)',
                            data: durationData,
                            backgroundColor: backgroundColors,
                            borderColor: borderColors,
                            borderWidth: 1
                        }]
                    },
                    options: {
                        responsive: true,
                        plugins: {
                            legend: {
                                display: false
                            },
                            title: {
                                display: true,
                                text: 'Test Duration'
                            }
                        },
                        scales: {
                            y: {
                                beginAtZero: true
                            }
                        }
                    }
                });
                console.log('Duration chart created');
            } catch (error) {
                console.error('Error creating duration chart:', error);
                document.getElementById('durationChart').insertAdjacentHTML('afterend', 
                    '<div style="color: red; text-align: center;">Error creating duration chart: ' + error.message + '</div>');
            }
        }
    </script>
</body>
</html>
