<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Algorithm Recommendations - MHA Flow</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.css" rel="stylesheet">
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-dark bg-dark sticky-top">
        <div class="container-fluid">
            <span class="navbar-brand mb-0 h1">
                <i class="fas fa-brain"></i> MHA Flow
            </span>
            <ul class="nav navbar-nav ms-auto">
                <li class="nav-item"><a class="nav-link" href="/">Home</a></li>
                <li class="nav-item"><a class="nav-link" href="/dashboard">Dashboard</a></li>
                <li class="nav-item"><a class="nav-link" href="/dataset-upload">Upload Data</a></li>
                <li class="nav-item"><a class="nav-link active" href="/algorithm-recommend">Recommend</a></li>
                <li class="nav-item"><a class="nav-link" href="/optimization">Optimize</a></li>
                <li class="nav-item"><a class="nav-link" href="/results">Results</a></li>
            </ul>
        </div>
    </nav>

    <div class="container-fluid py-5">
        <!-- Alert if no dataset loaded -->
        <div id="noDatasetAlert" class="alert alert-warning" style="display: none;">
            <i class="fas fa-exclamation-triangle"></i> Please <a href="/dataset-upload">upload and analyze a dataset</a> first.
        </div>

        <!-- Main Content -->
        <div id="mainContent" style="display: none;">
            <!-- Section 1: Dataset Overview -->
            <div class="row mb-5">
                <div class="col-lg-8 offset-lg-2">
                    <div class="card shadow-lg border-0">
                        <div class="card-header bg-gradient text-white py-4">
                            <h3 class="mb-0">
                                <i class="fas fa-database"></i> Dataset Overview
                            </h3>
                        </div>
                        <div class="card-body p-4">
                            <div class="row">
                                <div class="col-md-3 text-center">
                                    <div class="stat-card">
                                        <h4 id="overviewSamples" class="text-primary">-</h4>
                                        <p class="text-muted">Samples</p>
                                    </div>
                                </div>
                                <div class="col-md-3 text-center">
                                    <div class="stat-card">
                                        <h4 id="overviewFeatures" class="text-success">-</h4>
                                        <p class="text-muted">Features</p>
                                    </div>
                                </div>
                                <div class="col-md-3 text-center">
                                    <div class="stat-card">
                                        <h4 id="overviewComplexity" class="text-warning">-</h4>
                                        <p class="text-muted">Complexity</p>
                                    </div>
                                </div>
                                <div class="col-md-3 text-center">
                                    <div class="stat-card">
                                        <h4 id="overviewQuality" class="text-info">-</h4>
                                        <p class="text-muted">Quality</p>
                                    </div>
                                </div>
                            </div>
                            <hr>
                            <div class="row">
                                <div class="col-md-6">
                                    <h6 class="mb-3"><strong>Problem Type:</strong></h6>
                                    <div class="alert alert-info mb-0">
                                        <h5 id="recommendProblemType" class="mb-0">-</h5>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <h6 class="mb-3"><strong>Detected Characteristics:</strong></h6>
                                    <div id="recommendCharacteristics">
                                        <!-- Characteristics badges here -->
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Section 2: Recommended Algorithms Ranking -->
            <div class="row mb-5">
                <div class="col-lg-8 offset-lg-2">
                    <div class="card shadow-lg border-0">
                        <div class="card-header bg-gradient text-white py-4">
                            <h3 class="mb-0">
                                <i class="fas fa-ranking-star"></i> Recommended Algorithms (Ranked)
                            </h3>
                        </div>
                        <div class="card-body p-4">
                            <div id="recommendedAlgorithmsList">
                                <!-- Algorithm rankings will be inserted here -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Section 3: Algorithm Comparison Matrix -->
            <div class="row mb-5">
                <div class="col-lg-10 offset-lg-1">
                    <div class="card shadow-lg border-0">
                        <div class="card-header bg-gradient text-white py-4">
                            <h3 class="mb-0">
                                <i class="fas fa-table"></i> Algorithm Characteristics Comparison
                            </h3>
                        </div>
                        <div class="card-body p-4">
                            <div class="table-responsive">
                                <table class="table table-hover" id="comparisonTable">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Algorithm</th>
                                            <th>Exploration</th>
                                            <th>Exploitation</th>
                                            <th>Convergence</th>
                                            <th>Diversity</th>
                                            <th>Local Optima Avoidance</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <!-- Algorithm characteristics will be inserted here -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Section 4: Levify Transformation Options -->
            <div class="row mb-5">
                <div class="col-lg-8 offset-lg-2">
                    <div class="card shadow-lg border-0">
                        <div class="card-header bg-gradient text-white py-4">
                            <h3 class="mb-0">
                                <i class="fas fa-wand-magic-sparkles"></i> Levify Algorithm Transformation
                            </h3>
                        </div>
                        <div class="card-body p-4">
                            <p class="mb-4">
                                Transform any algorithm from Exploration → Exploitation or vice versa using Levify technology.
                            </p>
                            <div class="row mb-4">
                                <div class="col-md-6">
                                    <label for="levifyAlgorithm" class="form-label"><strong>Select Algorithm to Transform:</strong></label>
                                    <select class="form-select form-select-lg" id="levifyAlgorithm">
                                        <option value="">-- Choose an algorithm --</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label for="levifyTransformation" class="form-label"><strong>Transformation Type:</strong></label>
                                    <select class="form-select form-select-lg" id="levifyTransformation">
                                        <option value="">-- Choose transformation --</option>
                                        <option value="exploration">Boost Exploration</option>
                                        <option value="exploitation">Boost Exploitation</option>
                                        <option value="balanced">Balanced (50/50)</option>
                                    </select>
                                </div>
                            </div>
                            <div class="row mb-4">
                                <div class="col-md-12">
                                    <label for="levifyIntensity" class="form-label"><strong>Transformation Intensity (0 = subtle, 1 = extreme):</strong></label>
                                    <input type="range" class="form-range" id="levifyIntensity" min="0" max="1" step="0.1" value="0.7">
                                    <small class="text-muted">Current: <span id="intensityValue">0.7</span></small>
                                </div>
                            </div>
                            <button class="btn btn-primary btn-lg w-100" id="transformBtn">
                                <i class="fas fa-bolt"></i> Transform Algorithm
                            </button>
                            <div id="transformResult" class="mt-4" style="display: none;">
                                <div class="alert alert-success">
                                    <h5>Transformation Complete</h5>
                                    <div id="transformDetails"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Section 5: Algorithm Profiles -->
            <div class="row mb-5">
                <div class="col-lg-8 offset-lg-2">
                    <div class="card shadow-lg border-0">
                        <div class="card-header bg-gradient text-white py-4">
                            <h3 class="mb-0">
                                <i class="fas fa-info-circle"></i> Detailed Algorithm Profiles
                            </h3>
                        </div>
                        <div class="card-body p-4">
                            <div id="algorithmProfiles">
                                <!-- Individual algorithm profiles will be inserted here -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Action Buttons -->
            <div class="row mb-5">
                <div class="col-lg-8 offset-lg-2">
                    <a href="/optimization" class="btn btn-success btn-lg w-100">
                        <i class="fas fa-rocket"></i> Proceed to Optimization with Recommended Algorithm
                    </a>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
    <script>
        let datasetProfile = null;
        let allAlgorithms = [];

        // Initialize page
        async function initializeRecommendationPage() {
            try {
                const response = await fetch('/api/dataset/profile');
                
                if (response.status === 400) {
                    document.getElementById('noDatasetAlert').style.display = 'block';
                    return;
                }

                if (!response.ok) {
                    throw new Error('Failed to fetch dataset profile');
                }

                datasetProfile = await response.json();
                document.getElementById('mainContent').style.display = 'block';
                
                // Fetch all algorithms
                const algResponse = await fetch('/api/algorithms/list');
                const algData = await algResponse.json();
                allAlgorithms = algData.algorithms;

                displayDatasetOverview();
                displayRecommendedAlgorithms();
                displayComparisonMatrix();
                populateLevifySelect();
            } catch (error) {
                console.error('Error initializing page:', error);
                document.getElementById('noDatasetAlert').style.display = 'block';
            }
        }

        function displayDatasetOverview() {
            document.getElementById('overviewSamples').textContent = datasetProfile.n_samples;
            document.getElementById('overviewFeatures').textContent = datasetProfile.n_features;
            document.getElementById('overviewComplexity').textContent = (datasetProfile.complexity_score * 100).toFixed(0) + '%';
            document.getElementById('overviewQuality').textContent = (datasetProfile.quality_score * 100).toFixed(0) + '%';
            document.getElementById('recommendProblemType').textContent = datasetProfile.problem_type.toUpperCase();
            
            const charBadges = datasetProfile.characteristics.map(char => 
                `<span class="badge bg-primary me-2 mb-2">${char}</span>`
            ).join('');
            document.getElementById('recommendCharacteristics').innerHTML = charBadges;
        }

        function displayRecommendedAlgorithms() {
            const algorithms = datasetProfile.recommended_algorithms;
            const html = algorithms.map((algo, idx) => `
                <div class="algorithm-ranking mb-3">
                    <div class="d-flex align-items-center mb-2">
                        <span class="badge bg-primary me-3" style="font-size: 1.2em;">#{idx + 1}</span>
                        <h5 class="mb-0 flex-grow-1">${algo.name}</h5>
                        <span class="badge bg-success">${(algo.suitability_score * 100).toFixed(0)}% Match</span>
                    </div>
                    <p class="text-muted mb-2"><strong>Why recommended:</strong> ${algo.reason}</p>
                    <div class="progress" style="height: 8px;">
                        <div class="progress-bar bg-success" style="width: ${algo.suitability_score * 100}%"></div>
                    </div>
                </div>
            `).join('');
            document.getElementById('recommendedAlgorithmsList').innerHTML = html;
        }

        async function displayComparisonMatrix() {
            const tbody = document.querySelector('#comparisonTable tbody');
            const html = [];

            for (const algo of allAlgorithms.slice(0, 10)) {
                try {
                    const response = await fetch(`/api/algorithms/characteristics/${algo}`);
                    if (response.ok) {
                        const chars = await response.json();
                        html.push(`
                            <tr>
                                <td><strong>${algo}</strong></td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="progress flex-grow-1 me-2" style="height: 5px;">
                                            <div class="progress-bar" style="width: ${(chars.exploration_score || 0) * 100}%"></div>
                                        </div>
                                        <small>${((chars.exploration_score || 0) * 100).toFixed(0)}%</small>
                                    </div>
                                </td>
                                <td>
                                    <div class="d-flex align-items-center">
                                        <div class="progress flex-grow-1 me-2" style="height: 5px;">
                                            <div class="progress-bar bg-success" style="width: ${(chars.exploitation_score || 0) * 100}%"></div>
                                        </div>
                                        <small>${((chars.exploitation_score || 0) * 100).toFixed(0)}%</small>
                                    </div>
                                </td>
                                <td><span class="badge bg-info">${(chars.convergence_speed || 'N/A')}</span></td>
                                <td><span class="badge bg-warning">${(chars.diversity_maintenance || 'N/A')}</span></td>
                                <td><span class="badge bg-danger">${(chars.local_optima_avoidance || 'N/A')}</span></td>
                            </tr>
                        `);
                    }
                } catch (error) {
                    console.error(`Error fetching characteristics for ${algo}:`, error);
                }
            }

            tbody.innerHTML = html.join('');
        }

        function populateLevifySelect() {
            const select = document.getElementById('levifyAlgorithm');
            allAlgorithms.forEach(algo => {
                const option = document.createElement('option');
                option.value = algo;
                option.textContent = algo.toUpperCase();
                select.appendChild(option);
            });
        }

        // Levify transformation
        document.getElementById('levifyIntensity').addEventListener('input', (e) => {
            document.getElementById('intensityValue').textContent = e.target.value;
        });

        document.getElementById('transformBtn').addEventListener('click', async () => {
            const algo = document.getElementById('levifyAlgorithm').value;
            const transform = document.getElementById('levifyTransformation').value;
            const intensity = document.getElementById('levifyIntensity').value;

            if (!algo || !transform) {
                alert('Please select both algorithm and transformation type');
                return;
            }

            try {
                const response = await fetch('/api/levify/transform', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        algorithm_name: algo,
                        transformation: transform,
                        intensity: parseFloat(intensity)
                    })
                });

                if (!response.ok) {
                    throw new Error('Transformation failed');
                }

                const result = await response.json();
                displayTransformResult(result);
            } catch (error) {
                alert('Error: ' + error.message);
            }
        });

        function displayTransformResult(result) {
            const details = document.getElementById('transformDetails');
            const resultDiv = document.getElementById('transformResult');
            
            let html = `<h6>${result.original_algorithm} → ${result.transformation.toUpperCase()}</h6>`;
            html += '<h6 class="mt-3">Parameter Adjustments:</h6>';
            html += '<ul>';
            for (const [param, change] of Object.entries(result.parameter_adjustments || {})) {
                html += `<li><strong>${param}:</strong> ${change}</li>`;
            }
            html += '</ul>';

            details.innerHTML = html;
            resultDiv.style.display = 'block';
        }

        // Initialize on page load
        document.addEventListener('DOMContentLoaded', initializeRecommendationPage);
    </script>
</body>
</html>
