{% extends "base.html" %}

{% block title %}Upload Algorithm - MHA Flow{% endblock %}

{% block content %}
<div class="row justify-content-center">
    <div class="col-md-8">
        <div class="card shadow">
            <div class="card-header bg-warning">
                <h5><i class="fas fa-upload"></i> Upload Custom Algorithm</h5>
            </div>
            <div class="card-body">
                <div class="alert alert-info">
                    <h6><i class="fas fa-info-circle"></i> Requirements:</h6>
                    <ul class="mb-0">
                        <li>Python file (.py) with a class inheriting from <code>BaseOptimizer</code></li>
                        <li>Must implement <code>_optimize()</code> method</li>
                        <li>Method signature: <code>def _optimize(self, objective_function, X=None, y=None, **kwargs)</code></li>
                        <li>Must return: <code>(best_position, best_fitness, global_fitness, local_fitness, local_positions)</code></li>
                    </ul>
                </div>
                
                <form id="uploadForm" enctype="multipart/form-data">
                    <div class="mb-3">
                        <label class="form-label">Algorithm File</label>
                        <input type="file" class="form-control" id="algorithmFile" accept=".py" required>
                        <small class="form-text text-muted">Upload a Python file containing your algorithm</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Description (Optional)</label>
                        <textarea class="form-control" id="description" rows="4" placeholder="Describe your algorithm..."></textarea>
                    </div>
                    
                    <button type="submit" class="btn btn-warning w-100" id="uploadBtn">
                        <i class="fas fa-upload"></i> Upload Algorithm
                    </button>
                </form>
                
                <div id="uploadResult" class="mt-3 d-none"></div>
            </div>
        </div>
        
        <div class="card shadow mt-4">
            <div class="card-header bg-secondary text-white">
                <h5><i class="fas fa-code"></i> Example Template</h5>
            </div>
            <div class="card-body">
                <pre class="bg-light p-3 rounded"><code>from mha_toolbox.base import BaseOptimizer
import numpy as np

class MyCustomAlgorithm(BaseOptimizer):
    """Custom Optimization Algorithm"""
    
    def __init__(self, population_size=30, max_iterations=100, **kwargs):
        super().__init__(population_size, max_iterations, **kwargs)
        self.algorithm_name = "My Custom Algorithm"
    
    def _optimize(self, objective_function, X=None, y=None, **kwargs):
        # Get dimensions and bounds
        if X is not None:
            dimension = X.shape[1]
            lb, ub = 0.0, 1.0
        else:
            dimension = kwargs.get('dimensions', 10)
            lb = kwargs.get('lower_bound', -100.0)
            ub = kwargs.get('upper_bound', 100.0)
        
        # Initialize population
        population = np.random.uniform(lb, ub, (self.population_size_, dimension))
        fitness = np.array([objective_function(ind) for ind in population])
        
        # Find best solution
        best_idx = np.argmin(fitness)
        best_position = population[best_idx].copy()
        best_fitness = fitness[best_idx]
        
        # Tracking
        global_fitness = [best_fitness]
        local_fitness = [fitness.copy()]
        local_positions = [population.copy()]
        
        # Main optimization loop
        for iteration in range(self.max_iterations_):
            for i in range(self.population_size_):
                # Your optimization logic here
                # Update population[i]
                population[i] = np.clip(population[i], lb, ub)
                fitness[i] = objective_function(population[i])
                
                if fitness[i] < best_fitness:
                    best_position = population[i].copy()
                    best_fitness = fitness[i]
            
            global_fitness.append(best_fitness)
            local_fitness.append(fitness.copy())
            local_positions.append(population.copy())
        
        return best_position, best_fitness, global_fitness, local_fitness, local_positions</code></pre>
                <button class="btn btn-sm btn-outline-secondary" onclick="copyTemplate()">
                    <i class="fas fa-copy"></i> Copy Template
                </button>
            </div>
        </div>
    </div>
</div>

<script>
document.getElementById('uploadForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const fileInput = document.getElementById('algorithmFile');
    const description = document.getElementById('description').value;
    
    if (!fileInput.files.length) {
        alert('Please select a file');
        return;
    }
    
    const formData = new FormData();
    formData.append('file', fileInput.files[0]);
    formData.append('description', description);
    
    document.getElementById('uploadBtn').disabled = true;
    
    try {
        const response = await fetch('/api/upload-algorithm', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        const resultDiv = document.getElementById('uploadResult');
        
        if (response.ok) {
            resultDiv.className = 'alert alert-success mt-3';
            resultDiv.innerHTML = `
                <h6><i class="fas fa-check-circle"></i> Upload Successful!</h6>
                <p class="mb-0"><strong>Algorithm:</strong> ${result.algorithm_name}</p>
                <p class="mb-0">Your algorithm is now available for optimization.</p>
            `;
            fileInput.value = '';
            document.getElementById('description').value = '';
        } else {
            resultDiv.className = 'alert alert-danger mt-3';
            resultDiv.innerHTML = `
                <h6><i class="fas fa-exclamation-triangle"></i> Upload Failed</h6>
                <p class="mb-0">${result.error}</p>
                ${result.details ? '<pre>' + JSON.stringify(result.details, null, 2) + '</pre>' : ''}
            `;
        }
        
        resultDiv.classList.remove('d-none');
        
    } catch (error) {
        alert('Upload failed: ' + error.message);
    } finally {
        document.getElementById('uploadBtn').disabled = false;
    }
});

function copyTemplate() {
    const template = document.querySelector('pre code').textContent;
    navigator.clipboard.writeText(template).then(() => {
        alert('Template copied to clipboard!');
    });
}
</script>
{% endblock %}
