{% extends "base.html" %}

{% block title %}cuti - Agent Manager{% endblock %}

{% block head %}
<link rel="stylesheet" href="{{ url_for('static', path='css/agents.css') }}?v=4">
<link rel="stylesheet" href="{{ url_for('static', path='css/agent-cards.css') }}?v=1">
{% endblock %}

{% set body_class = "" %}
{% set alpine_data = "agentManager()" %}

{% block content %}
<div class="agents-page" :class="{ 'compact-mode': agents.length > 15 }">
    <!-- Sub Navigation -->
    <div class="sub-nav">
        <div class="nav-tabs">
            <a href="/agents" class="nav-tab active">
                <i class="fas fa-robot"></i>
                <span>Agents</span>
            </a>
            <a href="/tools" class="nav-tab">
                <i class="fas fa-wrench"></i>
                <span>Tools</span>
            </a>
        </div>
    </div>
    
    <!-- Sticky Page Header -->
    <div class="page-header">
        <div>
            <h1 class="page-title">Agent Manager</h1>
            <p class="page-subtitle">
                <span x-show="filteredAgents.length > 0" x-text="`${filteredAgents.length} of ${agents.length} agents`"></span>
                <span x-show="agents.length === 0">Create and manage custom Claude Code agents</span>
            </p>
            <!-- Orchestration Status -->
            <div class="orchestration-status" x-show="orchestrationEnabled">
                <div class="status-indicator active"></div>
                <span>Symphony Mode Active</span>
                <span class="active-count" x-text="`${activeAgents.size} agents orchestrated`"></span>
            </div>
        </div>
        <div class="page-actions">
            <!-- Search bar for filtering agents -->
            <div class="agent-search" x-show="agents.length > 5">
                <i class="fas fa-search"></i>
                <input type="text" 
                       x-model="searchQuery"
                       @input="filterAgents()"
                       placeholder="Search agents..."
                       class="search-input">
            </div>
            <a href="/orchestration" class="btn-secondary" title="Configure Orchestra">
                <i class="fas fa-sliders-h"></i>
                <span>Orchestra</span>
            </a>
            <button @click="toggleCompactMode()" 
                    x-show="agents.length > 10" 
                    class="btn-secondary"
                    title="Toggle compact view">
                <i class="fas" :class="compactMode ? 'fa-expand' : 'fa-compress'"></i>
            </button>
            <button @click="openCreateModal()" class="btn-primary">
                <i class="fas fa-plus"></i>
                <span>Create Agent</span>
            </button>
        </div>
    </div>
    
    <!-- Scrollable Container -->
    <div id="agents-container" class="agents-container agent-list" data-agents x-show="filteredAgents.length > 0" @scroll="handleScroll">
        <!-- Multi-Column Grid -->
        <div class="agents-grid">
            <template x-for="agent in filteredAgents" :key="agent.name">
            <div class="agent-card agent-item" 
                 :class="{
                     'agent-disabled': agent.agent_type === 'gemini' && !geminiAvailable,
                     'agent-active': activeAgents.has(agent.name),
                     'agent-orchestrated': orchestrationEnabled && activeAgents.has(agent.name)
                 }"
                 @click="toggleAgentCard(agent, $event)"
                 :title="activeAgents.has(agent.name) ? 'Click to deactivate' : 'Click to activate'">
                <!-- State Indicator - minimal dot -->
                <div class="agent-state-indicator"></div>
                
                <!-- Toggle Switch -->
                <div class="agent-toggle" @click.stop>
                    <input type="checkbox" 
                           class="toggle-switch"
                           :id="'toggle-' + agent.name"
                           :checked="activeAgents.has(agent.name)"
                           @change="toggleAgent(agent)">
                    <label :for="'toggle-' + agent.name" class="toggle-label"></label>
                </div>
                
                <div class="agent-card-header">
                    <div class="agent-name">
                        <span x-text="agent.name"></span>
                        <span x-show="agent.agent_type === 'gemini'" class="agent-badge-gemini">
                            <i class="fas fa-gem"></i>
                            <span>Gemini</span>
                        </span>
                        <span x-show="agent.is_builtin" class="agent-badge-builtin">
                            <span>Built-in</span>
                        </span>
                        <span x-show="!agent.is_builtin && isDefaultAgent(agent.name)" class="agent-badge">Default</span>
                        <span x-show="activeAgents.has(agent.name)" class="agent-badge-active">
                            <span>Active</span>
                        </span>
                    </div>
                </div>
                
                <div class="agent-description" x-text="agent.description || 'No description available'"></div>
                
                <div x-show="agent.agent_type === 'gemini' && !geminiAvailable" class="agent-warning">
                    <i class="fas fa-exclamation-triangle"></i>
                    <span>Gemini CLI not installed. Run: npm install -g @genkit-ai/cli</span>
                </div>
                
                <div class="agent-capabilities" x-show="agent.capabilities && agent.capabilities.length > 0">
                    <template x-for="cap in agent.capabilities" :key="cap">
                        <span class="capability-tag" x-text="cap"></span>
                    </template>
                </div>
                
                <div class="agent-tools" x-show="agent.tools && agent.tools.length > 0">
                    <i class="fas fa-tools"></i>
                    <span x-text="'Tools: ' + agent.tools.join(', ')"></span>
                </div>
                
                <div class="agent-footer">
                    <div class="agent-meta">
                        <span x-text="formatDate(agent.updated_at || agent.created_at)"></span>
                    </div>
                    <div class="agent-actions-row">
                        <button @click.stop="editAgent(agent)" class="btn-agent">
                            <i class="fas fa-edit"></i>
                            <span>Edit</span>
                        </button>
                        <button @click.stop="useAgent(agent)" 
                                :disabled="agent.agent_type === 'gemini' && !geminiAvailable"
                                :class="{
                                    'btn-agent': true, 
                                    'btn-use': true, 
                                    'btn-disabled': agent.agent_type === 'gemini' && !geminiAvailable,
                                    'btn-active': activeAgents.has(agent.name)
                                }"
                                :title="agent.agent_type === 'gemini' && !geminiAvailable ? 'Gemini CLI not installed' : activeAgents.has(agent.name) ? 'Agent is active in orchestra' : 'Use this agent'">
                            <i class="fas" :class="activeAgents.has(agent.name) ? 'fa-music' : 'fa-play'"></i>
                            <span x-text="activeAgents.has(agent.name) ? 'Active' : 'Use'"></span>
                        </button>
                        <button x-show="!agent.is_builtin && !isDefaultAgent(agent.name)" 
                                @click.stop="deleteAgent(agent.name)" 
                                class="btn-agent btn-delete">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            </div>
            </template>
        </div>
        
        <!-- Scroll hint for many agents -->
        <div class="scroll-hint" x-show="showScrollHint && filteredAgents.length > 20">
            <i class="fas fa-chevron-down"></i>
            <span>Scroll for more agents</span>
        </div>
    </div>
    
    <!-- No Results State -->
    <div x-show="agents.length > 0 && filteredAgents.length === 0" class="empty-state">
        <div class="empty-state-icon">🔍</div>
        <div class="empty-state-title">No agents found</div>
        <div class="empty-state-description">
            No agents match your search "<span x-text="searchQuery"></span>"
        </div>
    </div>
    
    <!-- Empty State -->
    <div x-show="agents.length === 0" class="empty-state">
        <div class="empty-state-icon">🤖</div>
        <div class="empty-state-title">No Custom Agents Yet</div>
        <div class="empty-state-description">
            Create your first Claude Code agent to automate specialized tasks and enhance your workflow
        </div>
    </div>
    
    <!-- Create/Edit Agent Modal -->
    <div x-show="showModal" class="modal-overlay" @click.self="closeModal()">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title" x-text="editingAgent ? 'Edit Agent' : 'Create New Agent'"></h2>
                <button @click="closeModal()" class="modal-close">&times;</button>
            </div>
            
            <div class="modal-body">
                <form @submit.prevent="saveAgent()" id="agentForm">
                    <!-- Simple creation flow for new agents -->
                    <template x-if="!editingAgent">
                        <div>
                            <div class="form-group">
                                <label class="form-label">Agent Name</label>
                                <input type="text" 
                                       x-model="formData.name" 
                                       class="form-input" 
                                       placeholder="e.g., test-writer, docs-generator"
                                       pattern="[a-z0-9-]+"
                                       required>
                                <div class="form-hint">Use lowercase letters and hyphens only</div>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Agent Purpose</label>
                                <textarea x-model="formData.description" 
                                          class="form-input" 
                                          style="min-height: 120px; font-family: inherit;"
                                          placeholder="Describe what this agent should do. For example: 'Write comprehensive unit tests for Python code with pytest, focusing on edge cases and error handling'"
                                          required></textarea>
                                <div class="form-hint">
                                    <i class="fas fa-magic"></i> Describe in plain language - Claude will create the detailed configuration
                                </div>
                            </div>
                        </div>
                    </template>
                    
                    <!-- Full editor for existing agents -->
                    <template x-if="editingAgent">
                        <div>
                            <div class="form-group">
                                <label class="form-label">Agent Name</label>
                                <input type="text" 
                                       x-model="formData.name" 
                                       :disabled="true"
                                       class="form-input">
                                <div class="form-hint">Agent names cannot be changed after creation</div>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Agent Prompt</label>
                                <div class="prompt-editor-wrapper">
                                    <div class="prompt-editor-header">
                                        <span class="editor-label">System Instructions</span>
                                        <div class="editor-tools">
                                            <button type="button" class="editor-tool-btn" @click="formatPrompt()" title="Format">
                                                <i class="fas fa-magic"></i> Format
                                            </button>
                                            <button type="button" class="editor-tool-btn" @click="clearPrompt()" title="Clear">
                                                <i class="fas fa-eraser"></i> Clear
                                            </button>
                                        </div>
                                    </div>
                                    <textarea x-model="formData.prompt" 
                                              @input="updateCharCount()"
                                              class="form-textarea" 
                                              style="border: none; background: transparent; padding: 16px;"
                                              placeholder="Define the agent's behavior, capabilities, and constraints..."
                                              required></textarea>
                                    <div class="prompt-editor-footer">
                                        <span class="char-count" :class="getCharCountClass()">
                                            <span x-text="promptCharCount"></span> / 4000 characters
                                        </span>
                                        <span>Markdown supported</span>
                                    </div>
                                </div>
                                <div class="form-hint">Write clear instructions that define the agent's expertise and behavior</div>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Capabilities</label>
                                <div class="tag-input-container">
                                    <template x-for="(cap, index) in formData.capabilities" :key="index">
                                        <span class="tag-item">
                                            <span x-text="cap"></span>
                                            <span @click="removeCapability(index)" class="tag-remove">&times;</span>
                                        </span>
                                    </template>
                                    <input type="text" 
                                           @keydown.enter.prevent="addCapability($event)"
                                           class="tag-input"
                                           placeholder="Add capability and press Enter">
                                </div>
                                <div class="form-hint">Agent capabilities (e.g., code-analysis, debugging, testing)</div>
                            </div>
                            
                            <div class="form-group">
                                <label class="form-label">Available Tools</label>
                                <div class="tag-input-container">
                                    <template x-for="(tool, index) in formData.tools" :key="index">
                                        <span class="tag-item">
                                            <span x-text="tool"></span>
                                            <span @click="removeTool(index)" class="tag-remove">&times;</span>
                                        </span>
                                    </template>
                                    <input type="text" 
                                           @keydown.enter.prevent="addTool($event)"
                                           class="tag-input"
                                           placeholder="Add tool and press Enter">
                                </div>
                                <div class="form-hint">Tools the agent can use (e.g., read, write, edit, bash)</div>
                            </div>
                        </div>
                    </template>
                </form>
            </div>
            
            <div class="modal-actions">
                <div class="modal-actions-info">
                    <i class="fas fa-info-circle"></i>
                    <span x-text="editingAgent ? 'Editing agent configuration' : 'Creating a new agent'"></span>
                </div>
                <div class="modal-actions-buttons">
                    <button type="button" @click="closeModal()" class="btn-modal btn-cancel">
                        <i class="fas fa-times"></i>
                        <span>Cancel</span>
                    </button>
                    <button type="submit" form="agentForm" class="btn-modal btn-primary" :disabled="!isFormValid()">
                        <i class="fas fa-save"></i>
                        <span x-text="editingAgent ? 'Update Agent' : 'Create Agent'"></span>
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
function agentManager() {
    return {
        agents: [],
        filteredAgents: [],
        searchQuery: '',
        showModal: false,
        editingAgent: null,
        compactMode: false,
        showScrollHint: true,
        geminiAvailable: false,
        orchestrationEnabled: false,
        activeAgents: new Set(),
        formData: {
            name: '',
            description: '',
            prompt: '',
            capabilities: [],
            tools: [],
            context_files_str: '',
            working_directory: null,
            environment: {}
        },
        promptCharCount: 0,
        defaultAgents: ['code-reviewer', 'test-writer', 'docs-generator', 'refactor-assistant', 'bug-hunter'],
        
        async init() {
            await this.loadAgents();
            await this.checkAgentStatus();
            await this.loadOrchestrationStatus();
            
            // Check Symphony Mode from localStorage
            this.orchestrationEnabled = localStorage.getItem('symphonyMode') === 'true';
            
            // Auto-enable compact mode for many agents
            this.compactMode = this.agents.length > 15;
            // Show scroll hint briefly
            if (this.filteredAgents.length > 20) {
                setTimeout(() => {
                    this.showScrollHint = false;
                }, 5000);
            }
            
            // Connect to WebSocket for real-time updates
            this.connectWebSocket();
        },
        
        connectWebSocket() {
            const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
            const ws = new WebSocket(`${protocol}//${window.location.host}/ws`);
            
            ws.onmessage = (event) => {
                const data = JSON.parse(event.data);
                if (data.type === 'agent_toggled' || data.type === 'agents_hot_swapped') {
                    this.loadOrchestrationStatus();
                }
                if (data.type === 'symphony_mode_changed') {
                    this.orchestrationEnabled = data.enabled;
                }
            };
        },
        
        async loadOrchestrationStatus() {
            try {
                const response = await fetch('/api/agents');
                if (response.ok) {
                    const agents = await response.json();
                    this.activeAgents.clear();
                    agents.forEach(agent => {
                        if (agent.enabled) {
                            this.activeAgents.add(agent.id);
                        }
                    });
                }
            } catch (error) {
                console.error('Failed to load orchestration status:', error);
            }
        },
        
        async toggleAgentCard(agent, event) {
            // Don't toggle if clicking on action buttons or if disabled
            if (event.target.closest('.btn-agent') || 
                (agent.agent_type === 'gemini' && !this.geminiAvailable)) {
                return;
            }
            
            const isActive = this.activeAgents.has(agent.name);
            const enabled = !isActive;
            
            try {
                const response = await fetch(`/api/agents/${agent.name}/toggle`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ enabled })
                });
                
                if (response.ok) {
                    if (enabled) {
                        this.activeAgents.add(agent.name);
                        this.showNotification(`${agent.name} activated in orchestra`, 'success');
                        // Add a subtle animation if card element exists
                        if (event.currentTarget) {
                            this.animateCardActivation(event.currentTarget);
                        }
                    } else {
                        this.activeAgents.delete(agent.name);
                        this.showNotification(`${agent.name} deactivated`, 'info');
                    }
                } else {
                    throw new Error('Failed to toggle agent');
                }
            } catch (error) {
                console.error('Failed to toggle agent:', error);
                this.showNotification('Failed to toggle agent', 'error');
            }
        },
        
        // Removed ripple and mouse position functions for minimalistic design
        
        animateCardActivation(card) {
            if (!card || !card.style) return;
            card.style.animation = 'none';
            setTimeout(() => {
                if (card && card.style) {
                    card.style.animation = '';
                }
            }, 10);
        },
        
        showNotification(message, type = 'info') {
            const notification = document.createElement('div');
            notification.className = `notification notification-${type}`;
            notification.innerHTML = `
                <i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : 'info-circle'}"></i>
                <span>${message}</span>
            `;
            
            document.body.appendChild(notification);
            
            setTimeout(() => notification.classList.add('show'), 10);
            
            setTimeout(() => {
                notification.classList.remove('show');
                setTimeout(() => notification.remove(), 300);
            }, 3000);
        },
        
        async checkAgentStatus() {
            try {
                const response = await fetch('/api/claude-code-agents/status');
                if (response.ok) {
                    const status = await response.json();
                    this.geminiAvailable = status.gemini_available;
                }
            } catch (error) {
                console.error('Error checking agent status:', error);
            }
        },
        
        async loadAgents() {
            try {
                const response = await fetch('/api/claude-code-agents/');
                if (response.ok) {
                    this.agents = await response.json();
                    this.filteredAgents = [...this.agents];
                }
            } catch (error) {
                console.error('Error loading agents:', error);
            }
        },
        
        isDefaultAgent(name) {
            return this.defaultAgents.includes(name);
        },
        
        openCreateModal() {
            this.editingAgent = null;
            this.formData = {
                name: '',
                description: '',
                prompt: '',
                capabilities: [],
                tools: [],
                context_files_str: '',
                working_directory: null,
                environment: {}
            };
            this.promptCharCount = 0;
            this.showModal = true;
        },
        
        editAgent(agent) {
            this.editingAgent = agent;
            this.formData = {
                name: agent.name,
                description: agent.description,
                content: agent.prompt,
                prompt: agent.prompt,
                capabilities: agent.capabilities || [],
                tools: agent.tools || []
            };
            this.promptCharCount = (agent.prompt || '').length;
            this.showModal = true;
        },
        
        closeModal() {
            this.showModal = false;
            this.editingAgent = null;
        },
        
        async saveAgent() {
            try {
                let response;
                if (this.editingAgent) {
                    // Update existing agent
                    response = await fetch(`/api/claude-code-agents/${this.editingAgent.name}`, {
                        method: 'PUT',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            content: this.formData.content || this.formData.prompt
                        })
                    });
                } else {
                    // Create new agent using Claude
                    this.showModal = false;
                    alert('Creating agent with Claude... This may take a moment.');
                    
                    response = await fetch('/api/claude-code-agents/create', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({
                            name: this.formData.name,
                            description: this.formData.description
                        })
                    });
                }
                
                if (response.ok) {
                    await this.loadAgents();
                    this.closeModal();
                    if (!this.editingAgent) {
                        alert('Agent created successfully!');
                    }
                } else {
                    const error = await response.json();
                    alert(error.detail || 'Error saving agent');
                    if (!this.editingAgent) {
                        this.showModal = true;
                    }
                }
            } catch (error) {
                console.error('Error saving agent:', error);
                alert('Error saving agent: ' + error.message);
            }
        },
        
        async deleteAgent(name) {
            if (!confirm(`Are you sure you want to delete the agent "${name}"?`)) {
                return;
            }
            
            try {
                const response = await fetch(`/api/claude-code-agents/${name}`, {
                    method: 'DELETE'
                });
                
                if (response.ok) {
                    await this.loadAgents();
                } else {
                    const error = await response.json();
                    alert(error.detail || 'Error deleting agent');
                }
            } catch (error) {
                console.error('Error deleting agent:', error);
                alert('Error deleting agent');
            }
        },
        
        useAgent(agent) {
            // Navigate to chat with agent pre-selected
            // Store the agent name in sessionStorage so the chat can pick it up
            sessionStorage.setItem('selectedAgent', `@${agent.name}`);
            window.location.href = '/';
        },
        
        addCapability(event) {
            const value = event.target.value.trim();
            if (value && !this.formData.capabilities.includes(value)) {
                this.formData.capabilities.push(value);
                event.target.value = '';
            }
        },
        
        removeCapability(index) {
            this.formData.capabilities.splice(index, 1);
        },
        
        addTool(event) {
            const value = event.target.value.trim();
            if (value && !this.formData.tools.includes(value)) {
                this.formData.tools.push(value);
                event.target.value = '';
            }
        },
        
        removeTool(index) {
            this.formData.tools.splice(index, 1);
        },
        
        formatDate(dateStr) {
            if (!dateStr) return 'Recently created';
            const date = new Date(dateStr);
            const now = new Date();
            const diff = now - date;
            const days = Math.floor(diff / (1000 * 60 * 60 * 24));
            
            if (days === 0) return 'Today';
            if (days === 1) return 'Yesterday';
            if (days < 7) return `${days} days ago`;
            if (days < 30) return `${Math.floor(days / 7)} weeks ago`;
            return date.toLocaleDateString();
        },
        
        toggleMenu(agentName) {
            // Implement dropdown menu if needed
        },
        
        updateCharCount() {
            this.promptCharCount = this.formData.prompt.length;
        },
        
        getCharCountClass() {
            if (this.promptCharCount > 4000) return 'error';
            if (this.promptCharCount > 3500) return 'warning';
            return '';
        },
        
        formatPrompt() {
            // Simple formatting - trim whitespace and ensure proper line breaks
            this.formData.prompt = this.formData.prompt
                .split('\n')
                .map(line => line.trim())
                .filter(line => line || this.formData.prompt.includes('\n\n'))
                .join('\n');
            this.updateCharCount();
        },
        
        clearPrompt() {
            if (confirm('Are you sure you want to clear the prompt?')) {
                this.formData.prompt = '';
                this.updateCharCount();
            }
        },
        
        isFormValid() {
            if (this.editingAgent) {
                return this.formData.name && 
                       this.formData.description && 
                       this.formData.prompt && 
                       this.promptCharCount <= 4000;
            } else {
                return this.formData.name && this.formData.description;
            }
        },
        
        toggleCompactMode() {
            this.compactMode = !this.compactMode;
            // Force reflow for smooth transition
            const container = document.querySelector('.agents-page');
            if (container) {
                container.classList.toggle('compact-mode', this.compactMode);
            }
        },
        
        handleScroll(event) {
            // Hide scroll hint once user starts scrolling
            if (this.showScrollHint && event.target.scrollTop > 100) {
                this.showScrollHint = false;
            }
        },
        
        filterAgents() {
            const query = this.searchQuery.toLowerCase().trim();
            if (!query) {
                this.filteredAgents = [...this.agents];
            } else {
                this.filteredAgents = this.agents.filter(agent => {
                    return agent.name.toLowerCase().includes(query) ||
                           (agent.description && agent.description.toLowerCase().includes(query)) ||
                           (agent.capabilities && agent.capabilities.some(cap => cap.toLowerCase().includes(query))) ||
                           (agent.tools && agent.tools.some(tool => tool.toLowerCase().includes(query)));
                });
            }
            
            // Sort active agents first
            this.filteredAgents.sort((a, b) => {
                const aActive = this.activeAgents.has(a.name);
                const bActive = this.activeAgents.has(b.name);
                if (aActive && !bActive) return -1;
                if (!aActive && bActive) return 1;
                return 0;
            });
        }
    }
}
</script>
{% endblock %}