{% extends "base.html" %}

{% block title %}Create Manifest - AgentOS{% endblock %}

{% block content %}
<div x-data="manifestCreator()" class="flex flex-col flex-1">
    <div class="page-header">
        <h2 class="page-title">🛠️ Create Agent Manifest</h2>
        <button @click="resetForm()" class="btn btn-primary">🔄 Reset</button>
    </div>
    
    <div class="form-container">
        <form @submit.prevent="generateManifest()">
            <!-- Agent Name -->
            <div class="form-group">
                <label class="form-label">Agent Name *</label>
                <input 
                    type="text" 
                    x-model="form.name" 
                    placeholder="my_assistant"
                    class="form-input"
                    required
                >
                <p class="text-xs text-gray-400 mt-1">A unique name for your agent</p>
            </div>
            
            <!-- Model Provider -->
            <div class="form-group">
                <label class="form-label">Model Provider *</label>
                <select x-model="form.provider" @change="updateModelOptions()" class="form-select" required>
                    <option value="">Select provider...</option>
                    <option value="github">GitHub Models</option>
                    <option value="openai">OpenAI</option>
                    <option value="claude">Anthropic Claude</option>
                    <option value="gemini">Google Gemini</option>
                    <option value="ollama">Ollama (Local)</option>
                    <option value="cohere">Cohere</option>
                </select>
            </div>
            
            <!-- Model Version -->
            <div class="form-group">
                <label class="form-label">Model Version *</label>
                <div x-show="loadingModels" class="flex items-center gap-2 p-3 bg-gray-700 rounded">
                    <div class="loading"></div>
                    <span class="text-sm text-gray-300">Loading models...</span>
                </div>
                <select x-show="!loadingModels" x-model="form.model" class="form-select" required :disabled="!form.provider">
                    <option value="">Select model...</option>
                    <template x-for="model in availableModels" :key="model.value">
                        <option :value="model.value" x-text="model.label"></option>
                    </template>
                </select>
                <p class="text-xs text-gray-400 mt-1" x-show="form.provider === 'ollama'">
                    ⚠️ Make sure the model is installed locally with: ollama pull &lt;model&gt;
                </p>
                <p class="text-xs text-red-400 mt-1" x-show="modelError" x-text="modelError"></p>
            </div>
            
            <!-- Isolation -->
            <div class="form-group">
                <label class="flex items-center gap-3 cursor-pointer">
                    <input 
                        type="checkbox" 
                        x-model="form.isolated"
                        class="w-5 h-5 rounded border-gray-600 bg-gray-700 text-blue-600 focus:ring-2 focus:ring-blue-500"
                    >
                    <div>
                        <span class="form-label mb-0">Enable Sandboxing</span>
                        <p class="text-xs text-gray-400">Run agent in isolated environment (recommended)</p>
                    </div>
                </label>
            </div>
            
            <!-- Advanced Options -->
            <div class="form-group">
                <button 
                    type="button"
                    @click="showAdvanced = !showAdvanced"
                    class="btn-link text-left"
                >
                    <span x-show="!showAdvanced">▶ Show Advanced Options</span>
                    <span x-show="showAdvanced">▼ Hide Advanced Options</span>
                </button>
            </div>
            
            <div x-show="showAdvanced" class="space-y-4">
                <!-- Scheduling -->
                <div class="form-group">
                    <label class="form-label">Schedule (Optional)</label>
                    <div class="grid grid-cols-2 gap-4">
                        <div>
                            <label class="text-xs text-gray-400">Daily at (hour 0-23)</label>
                            <input 
                                type="number" 
                                x-model.number="form.time"
                                min="0"
                                max="23"
                                placeholder="e.g., 14 for 2 PM"
                                class="form-input"
                            >
                        </div>
                        <div>
                            <label class="text-xs text-gray-400">Repeat every (minutes)</label>
                            <input 
                                type="number" 
                                x-model.number="form.repeat"
                                min="1"
                                placeholder="e.g., 30"
                                class="form-input"
                            >
                        </div>
                    </div>
                </div>
                
                <!-- Blocked Commands -->
                <div class="form-group">
                    <label class="form-label">Blocked Commands</label>
                    <textarea 
                        x-model="form.blockedCommands"
                        placeholder="rm&#10;sudo&#10;dd"
                        class="form-textarea"
                        rows="4"
                    ></textarea>
                    <p class="text-xs text-gray-400 mt-1">One command per line</p>
                </div>
            </div>
            
            <!-- Preview -->
            <div class="form-group" x-show="preview">
                <label class="form-label">Preview</label>
                <pre class="bg-gray-900 text-green-400 p-4 rounded-lg text-sm overflow-auto border border-gray-700" x-text="preview"></pre>
            </div>
            
            <!-- Actions -->
            <div class="flex gap-3">
                <button 
                    type="button"
                    @click="generatePreview()"
                    class="btn btn-primary"
                >
                    👁️ Preview
                </button>
                <button 
                    type="submit"
                    class="btn btn-primary"
                    style="background: linear-gradient(135deg, #10b981 0%, #059669 100%);"
                >
                    💾 Download Manifest
                </button>
            </div>
        </form>
    </div>
    
    <!-- Quick Templates -->
    <div class="form-container">
        <h3 class="form-label">⚡ Quick Templates</h3>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
            <button @click="loadTemplate('basic')" class="btn btn-primary text-left p-4">
                <div class="font-semibold">🚀 Basic Agent</div>
                <div class="text-xs text-gray-400">Simple agent with GitHub Models</div>
            </button>
            <button @click="loadTemplate('scheduled')" class="btn btn-primary text-left p-4">
                <div class="font-semibold">🕰️ Scheduled Agent</div>
                <div class="text-xs text-gray-400">Agent with daily schedule</div>
            </button>
            <button @click="loadTemplate('local')" class="btn btn-primary text-left p-4">
                <div class="font-semibold">🏠 Local Agent</div>
                <div class="text-xs text-gray-400">Using Ollama locally</div>
            </button>
        </div>
    </div>
</div>

<script>
function manifestCreator() {
    return {
        form: {
            name: 'my_assistant',
            provider: '',
            model: '',
            isolated: true,
            time: null,
            repeat: null,
            blockedCommands: 'rm\nrmdir\nsudo\ndd\nmkfs\nformat'
        },
        showAdvanced: false,
        preview: '',
        availableModels: [],
        loadingModels: false,
        modelError: '',
        
        async updateModelOptions() {
            this.form.model = '';
            this.availableModels = [];
            this.modelError = '';
            
            if (!this.form.provider) return;
            
            this.loadingModels = true;
            
            try {
                if (this.form.provider === 'github') {
                    await this.fetchGitHubModels();
                } else if (this.form.provider === 'openai') {
                    await this.fetchOpenAIModels();
                } else if (this.form.provider === 'ollama') {
                    await this.fetchOllamaModels();
                } else {
                    // Fallback for providers without API
                    this.loadStaticModels();
                }
            } catch (error) {
                console.error('Error fetching models:', error);
                this.modelError = 'Failed to fetch models. Using fallback list.';
                this.loadStaticModels();
            } finally {
                this.loadingModels = false;
            }
        },
        
        async fetchGitHubModels() {
            const response = await fetch('https://models.github.com/models');
            if (response.ok) {
                const data = await response.json();
                this.availableModels = data.map(m => ({
                    value: m.name,
                    label: `${m.name} ${m.summary ? '- ' + m.summary : ''}`
                }));
            } else {
                throw new Error('GitHub API failed');
            }
        },
        
        async fetchOpenAIModels() {
            // OpenAI requires API key, use static list
            this.availableModels = [
                { value: 'gpt-4o', label: 'GPT-4o (Latest)' },
                { value: 'gpt-4o-mini', label: 'GPT-4o Mini (Fast & Affordable)' },
                { value: 'gpt-4-turbo', label: 'GPT-4 Turbo' },
                { value: 'gpt-4', label: 'GPT-4' },
                { value: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo' }
            ];
        },
        
        async fetchOllamaModels() {
            try {
                const response = await fetch('http://localhost:11434/api/tags');
                if (response.ok) {
                    const data = await response.json();
                    if (data.models && data.models.length > 0) {
                        this.availableModels = data.models.map(m => ({
                            value: m.name,
                            label: `${m.name} (${(m.size / 1e9).toFixed(1)}GB)`
                        }));
                    } else {
                        throw new Error('No models installed');
                    }
                } else {
                    throw new Error('Ollama not running');
                }
            } catch (error) {
                this.modelError = '⚠️ Ollama not running or no models installed. Using common models.';
                this.availableModels = [
                    { value: 'llama3.1:8b', label: 'Llama 3.1 8B' },
                    { value: 'llama3.1:70b', label: 'Llama 3.1 70B' },
                    { value: 'llama3.2:3b', label: 'Llama 3.2 3B' },
                    { value: 'mistral:7b', label: 'Mistral 7B' },
                    { value: 'codellama:13b', label: 'Code Llama 13B' },
                    { value: 'qwen2.5-coder:7b', label: 'Qwen 2.5 Coder 7B' }
                ];
            }
        },
        
        loadStaticModels() {
            const staticModels = {
                claude: [
                    { value: 'claude-3-5-sonnet-20241022', label: 'Claude 3.5 Sonnet (Latest)' },
                    { value: 'claude-3-opus-20240229', label: 'Claude 3 Opus' },
                    { value: 'claude-3-sonnet-20240229', label: 'Claude 3 Sonnet' },
                    { value: 'claude-3-haiku-20240307', label: 'Claude 3 Haiku' }
                ],
                gemini: [
                    { value: 'gemini-1.5-pro', label: 'Gemini 1.5 Pro' },
                    { value: 'gemini-1.5-flash', label: 'Gemini 1.5 Flash' },
                    { value: 'gemini-pro', label: 'Gemini Pro' }
                ],
                cohere: [
                    { value: 'command-r-plus', label: 'Command R+' },
                    { value: 'command-r', label: 'Command R' },
                    { value: 'command', label: 'Command' }
                ]
            };
            this.availableModels = staticModels[this.form.provider] || [];
        },
        
        generatePreview() {
            this.preview = this.buildYaml();
        },
        
        buildYaml() {
            let yaml = `# AgentOS Configuration\n`;
            yaml += `name: ${this.form.name}\n`;
            yaml += `model_provider: ${this.form.provider}\n`;
            yaml += `model_version: ${this.form.model}\n`;
            yaml += `isolated: ${this.form.isolated}\n`;
            
            if (this.form.time !== null && this.form.time !== '') {
                yaml += `\n# Schedule to run daily at ${this.form.time}:00\n`;
                yaml += `time: ${this.form.time}\n`;
            }
            
            if (this.form.repeat !== null && this.form.repeat !== '') {
                yaml += `\n# Repeat every ${this.form.repeat} minutes\n`;
                yaml += `repeat: ${this.form.repeat}\n`;
            }
            
            if (this.form.blockedCommands.trim()) {
                yaml += `\n# Security: Blocked commands\n`;
                yaml += `DESTRUCTIVE_COMMANDS:\n`;
                const commands = this.form.blockedCommands.split('\n').filter(c => c.trim());
                commands.forEach(cmd => {
                    yaml += `  - ${cmd.trim()}\n`;
                });
            }
            
            return yaml;
        },
        
        generateManifest() {
            if (!this.form.name || !this.form.provider || !this.form.model) {
                alert('Please fill in all required fields');
                return;
            }
            
            const yaml = this.buildYaml();
            const blob = new Blob([yaml], { type: 'text/yaml' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `${this.form.name}.yaml`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
            
            // Show success message
            alert(`✅ Manifest downloaded: ${this.form.name}.yaml`);
        },
        
        loadTemplate(type) {
            if (type === 'basic') {
                this.form = {
                    name: 'basic_assistant',
                    provider: 'github',
                    model: 'openai/gpt-4o-mini',
                    isolated: true,
                    time: null,
                    repeat: null,
                    blockedCommands: 'rm\nrmdir\nsudo\ndd\nmkfs\nformat'
                };
            } else if (type === 'scheduled') {
                this.form = {
                    name: 'scheduled_assistant',
                    provider: 'github',
                    model: 'openai/gpt-4o-mini',
                    isolated: false,
                    time: 14,
                    repeat: 30,
                    blockedCommands: 'rm\nrmdir\nsudo\ndd\nformat'
                };
                this.showAdvanced = true;
            } else if (type === 'local') {
                this.form = {
                    name: 'local_assistant',
                    provider: 'ollama',
                    model: 'llama3.1:8b',
                    isolated: true,
                    time: null,
                    repeat: null,
                    blockedCommands: 'rm\nrmdir\nsudo\ndd\nmkfs\nformat'
                };
            }
            this.updateModelOptions();
            this.generatePreview();
        },
        
        resetForm() {
            this.form = {
                name: 'my_assistant',
                provider: '',
                model: '',
                isolated: true,
                time: null,
                repeat: null,
                blockedCommands: 'rm\nrmdir\nsudo\ndd\nmkfs\nformat'
            };
            this.showAdvanced = false;
            this.preview = '';
            this.availableModels = [];
        }
    }
}
</script>

<style>
.grid {
    display: grid;
}

.grid-cols-1 {
    grid-template-columns: repeat(1, minmax(0, 1fr));
}

.grid-cols-2 {
    grid-template-columns: repeat(2, minmax(0, 1fr));
}

@media (min-width: 768px) {
    .md\:grid-cols-3 {
        grid-template-columns: repeat(3, minmax(0, 1fr));
    }
}

.space-y-4 > * + * {
    margin-top: 1rem;
}
</style>
{% endblock %}
