{% extends "base.html" %}

{% block title %}Agents - AgentOS{% endblock %}

{% block content %}
<div x-data="agentsPage()" x-init="init()">
    <div class="flex justify-between items-center mb-6">
        <h2 class="text-2xl font-bold">🤖 Agents</h2>
        <div class="space-x-2">
            <button @click="refreshData()" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                🔄 Refresh
            </button>
            <button @click="pruneAgents()" class="bg-red-600 text-white px-4 py-2 rounded-lg hover:bg-red-700">
                🧹 Prune
            </button>
        </div>
    </div>
    
    <div class="bg-gray-800 rounded-lg shadow overflow-hidden border border-gray-700">
        <table class="w-full">
            <thead class="bg-gray-700">
                <tr>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase">ID</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase">Name</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase">Model</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase">Status</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase">PID</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase">Started</th>
                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-300 uppercase">Actions</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-700">
                <template x-for="agent in agents" :key="agent.id">
                    <tr>
                        <td class="px-6 py-4 text-sm font-mono text-gray-300" x-text="agent.id.substring(0, 8)"></td>
                        <td class="px-6 py-4 text-sm font-medium text-gray-100" x-text="agent.name"></td>
                        <td class="px-6 py-4 text-sm text-gray-300" x-text="agent.model"></td>
                        <td class="px-6 py-4 text-sm">
                            <span :class="getStatusClass(agent.status)" x-text="agent.status"></span>
                        </td>
                        <td class="px-6 py-4 text-sm text-gray-300" x-text="agent.pid || 'N/A'"></td>
                        <td class="px-6 py-4 text-sm text-gray-400" x-text="formatDate(agent.started_at)"></td>
                        <td class="px-6 py-4 text-sm space-x-2">
                            <button @click="viewLogs(agent)" class="text-blue-400 hover:text-blue-300">Logs</button>
                            <button x-show="agent.status === 'running'" @click="stopAgent(agent.id)" class="text-red-400 hover:text-red-300">Stop</button>
                        </td>
                    </tr>
                </template>
            </tbody>
        </table>
        
        <div x-show="agents.length === 0" class="p-8 text-center text-gray-400">
            <p>No agents found.</p>
            <a href="/run-agent" class="text-blue-400 hover:text-blue-300">Run your first agent →</a>
        </div>
    </div>
    
    <!-- Logs Modal -->
    <div x-show="showLogs" class="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50" @click.self="showLogs = false">
        <div class="bg-gray-800 rounded-lg shadow-xl max-w-4xl w-full mx-4 max-h-[80vh] flex flex-col border border-gray-700">
            <div class="p-6 border-b border-gray-700 flex justify-between items-center">
                <h3 class="text-lg font-semibold text-gray-100">📋 Logs: <span x-text="selectedAgent?.name"></span></h3>
                <button @click="showLogs = false" class="text-gray-400 hover:text-gray-200">✕</button>
            </div>
            <div class="flex-1 overflow-auto p-6">
                <pre class="bg-gray-900 text-green-400 p-4 rounded-lg text-sm overflow-auto border border-gray-700" x-text="logs"></pre>
            </div>
        </div>
    </div>
</div>

<script>
function agentsPage() {
    return {
        agents: {{ agents | tojson }},
        showLogs: false,
        selectedAgent: null,
        logs: '',
        
        init() {
            this.refreshData();
        },
        
        refreshData() {
            fetch('/api/agents')
                .then(r => r.json())
                .then(data => this.agents = data);
        },
        
        getStatusClass(status) {
            const classes = {
                'running': 'px-2 py-1 text-xs rounded-full bg-green-900 text-green-300 border border-green-700',
                'completed': 'px-2 py-1 text-xs rounded-full bg-blue-900 text-blue-300 border border-blue-700',
                'failed': 'px-2 py-1 text-xs rounded-full bg-red-900 text-red-300 border border-red-700',
                'stopped': 'px-2 py-1 text-xs rounded-full bg-gray-700 text-gray-300 border border-gray-600'
            };
            return classes[status] || classes['stopped'];
        },
        
        formatDate(dateStr) {
            if (!dateStr) return 'N/A';
            return new Date(dateStr).toLocaleString();
        },
        
        viewLogs(agent) {
            this.selectedAgent = agent;
            this.logs = 'Loading logs...';
            this.showLogs = true;
            
            fetch(`/api/agent/${agent.id}/logs`)
                .then(r => r.json())
                .then(data => {
                    if (data.logs) {
                        this.logs = data.logs.join('\n') || 'No logs available';
                    } else {
                        this.logs = 'Error loading logs: ' + (data.error || 'Unknown error');
                    }
                });
        },
        
        stopAgent(agentId) {
            if (confirm('Stop this agent?')) {
                fetch(`/api/agent/${agentId}/stop`, { method: 'POST' })
                    .then(r => r.json())
                    .then(data => {
                        if (data.success) {
                            this.refreshData();
                        } else {
                            alert('Failed to stop agent: ' + data.error);
                        }
                    });
            }
        },
        
        pruneAgents() {
            if (confirm('Remove all stopped agents?')) {
                fetch('/api/prune', { method: 'POST' })
                    .then(r => r.json())
                    .then(data => {
                        if (data.success) {
                            this.refreshData();
                        } else {
                            alert('Failed to prune agents: ' + data.error);
                        }
                    });
            }
        }
    }
}

// Global refresh function
function refreshData() {
    if (window.Alpine) {
        document.querySelector('[x-data]').__x.$data.refreshData();
    }
}
</script>
{% endblock %}