{% extends "base.html" %}

{% block title %}Autonomous Actions - {{ app_name }}{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row mb-4">
        <div class="col">
            <h2><i class="bi bi-robot"></i> Autonomous Actions</h2>
            <p class="text-muted">Schedule and manage AI-driven automated tasks</p>
        </div>
        <div class="col-auto">
            <button class="btn btn-outline-primary me-2" onclick="showAICreateModal()">
                <i class="bi bi-robot"></i> Create with AI
            </button>
            <button class="btn btn-primary" onclick="showCreateModal()">
                <i class="bi bi-plus-circle"></i> Create Action
            </button>
        </div>
    </div>

    <!-- Failed Actions Warning -->
    <div id="failed-warning" class="alert alert-warning d-none" role="alert">
        <i class="bi bi-exclamation-triangle-fill"></i>
        <span id="failed-count-text"></span>
    </div>

    <!-- Actions Table -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <span><i class="bi bi-list-task"></i> Actions</span>
            <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" id="showDisabled" checked onchange="loadActions()">
                <label class="form-check-label" for="showDisabled">Show disabled</label>
            </div>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0" id="actions-table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                            <th>Model</th>
                            <th>Schedule</th>
                            <th>Context</th>
                            <th>Status</th>
                            <th>Last Run</th>
                            <th>Failures</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="actions-tbody">
                        <tr>
                            <td colspan="9" class="text-center text-muted py-4">
                                <output class="spinner-border spinner-border-sm"></output>
                                Loading actions...
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Recent Runs -->
    <div class="card mt-4">
        <div class="card-header">
            <i class="bi bi-clock-history"></i> Recent Runs
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0" id="runs-table">
                    <thead>
                        <tr>
                            <th>Run ID</th>
                            <th>Action</th>
                            <th>Started</th>
                            <th>Status</th>
                            <th>Duration</th>
                            <th>Tokens</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="runs-tbody">
                        <tr>
                            <td colspan="7" class="text-center text-muted py-4">
                                <output class="spinner-border spinner-border-sm"></output>
                                Loading recent runs...
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Create/Edit Action Modal -->
<div class="modal fade" id="actionModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="actionModalTitle">Create Action</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="actionForm">
                    <input type="hidden" id="actionId">

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="actionName" class="form-label">Name *</label>
                            <input type="text" class="form-control" id="actionName" required maxlength="100">
                        </div>
                        <div class="col-md-6">
                            <label for="actionModel" class="form-label">Model *</label>
                            <select class="form-select" id="actionModel" required>
                                <option value="">Select a model...</option>
                            </select>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label for="actionDescription" class="form-label">Description *</label>
                        <input type="text" class="form-control" id="actionDescription" required maxlength="500">
                    </div>

                    <div class="mb-3">
                        <label for="actionPrompt" class="form-label">Action Prompt *</label>
                        <textarea class="form-control" id="actionPrompt" rows="5" required
                            placeholder="Describe the task for the AI to perform..."></textarea>
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-4">
                            <label for="scheduleType" class="form-label">Schedule Type *</label>
                            <select class="form-select" id="scheduleType" required onchange="updateScheduleConfig()">
                                <option value="one_off">One-off</option>
                                <option value="recurring">Recurring</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="contextMode" class="form-label">Context Mode</label>
                            <select class="form-select" id="contextMode">
                                <option value="fresh">Fresh (new context each run)</option>
                                <option value="cumulative">Cumulative (retains context)</option>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="maxFailures" class="form-label">Max Failures</label>
                            <input type="number" class="form-control" id="maxFailures" value="3" min="1" max="100">
                        </div>
                    </div>

                    <!-- One-off schedule config -->
                    <div id="oneOffConfig" class="mb-3">
                        <label for="runDate" class="form-label">Run Date/Time *</label>
                        <input type="datetime-local" class="form-control" id="runDate">
                    </div>

                    <!-- Recurring schedule config -->
                    <div id="recurringConfig" class="mb-3 d-none">
                        <label for="cronExpression" class="form-label">Cron Expression *</label>
                        <input type="text" class="form-control" id="cronExpression" placeholder="0 9 * * *">
                        <div class="form-text">
                            Examples: <code>0 9 * * *</code> (daily at 9am),
                            <code>0 9 * * MON</code> (Mondays at 9am),
                            <code>0 */6 * * *</code> (every 6 hours)
                        </div>
                    </div>

                    <!-- Tool Permissions -->
                    <div class="mb-3">
                        <span class="form-label d-block">Tool Permissions</span>
                        <div class="card">
                            <div class="card-body" style="max-height: 200px; overflow-y: auto;">
                                <div id="toolPermissions">
                                    <p class="text-muted mb-0">Loading available tools...</p>
                                </div>
                            </div>
                        </div>
                        <div class="form-text">Select which tools this action can use</div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="saveAction()">
                    <i class="bi bi-save"></i> Save Action
                </button>
            </div>
        </div>
    </div>
</div>

<!-- View Action Details Modal -->
<div class="modal fade" id="viewActionModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Action Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="viewActionBody">
                <!-- Populated by JavaScript -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Action Runs Modal -->
<div class="modal fade" id="actionRunsModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="actionRunsTitle">Action Runs</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Run ID</th>
                                <th>Started</th>
                                <th>Completed</th>
                                <th>Status</th>
                                <th>Tokens</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody id="actionRunsTbody">
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Run Details Modal -->
<div class="modal fade" id="runDetailsModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Run Details</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="runDetailsBody">
                <!-- Populated by JavaScript -->
            </div>
            <div class="modal-footer">
                <div class="me-auto">
                    <button type="button" class="btn btn-outline-secondary" onclick="exportRun('text')">
                        <i class="bi bi-file-text"></i> Export Text
                    </button>
                    <button type="button" class="btn btn-outline-secondary" onclick="exportRun('html')">
                        <i class="bi bi-filetype-html"></i> Export HTML
                    </button>
                    <button type="button" class="btn btn-outline-secondary" onclick="exportRun('markdown')">
                        <i class="bi bi-markdown"></i> Export Markdown
                    </button>
                </div>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Confirm Delete Modal -->
<div class="modal fade" id="confirmDeleteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title"><i class="bi bi-exclamation-triangle"></i> Confirm Delete</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete this action?</p>
                <p class="text-danger"><strong id="deleteActionName"></strong></p>
                <p class="text-muted small">This will also delete all run history for this action.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">
                    <i class="bi bi-trash"></i> Delete
                </button>
            </div>
        </div>
    </div>
</div>

<!-- AI-Assisted Action Creation Modal -->
<div class="modal fade" id="aiCreateModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="bi bi-robot"></i> Create Action with AI
                </h5>
                <button type="button" class="btn-close" onclick="cancelAICreation()"></button>
            </div>
            <div class="modal-body">
                <!-- Initial Setup Form -->
                <div id="aiCreateSetup">
                    <p class="text-muted mb-4">
                        Use AI to help you create an autonomous action through conversation.
                        The AI will ask questions to understand what you need and configure the action for you.
                    </p>

                    <div class="mb-3">
                        <label for="aiActionName" class="form-label">Action Name *</label>
                        <input type="text" class="form-control" id="aiActionName" required maxlength="100"
                               placeholder="e.g., Daily Report Generator">
                    </div>

                    <div class="mb-3">
                        <label for="aiActionDescription" class="form-label">Description *</label>
                        <input type="text" class="form-control" id="aiActionDescription" required maxlength="500"
                               placeholder="Brief description of what this action should do">
                    </div>

                    <div class="mb-3">
                        <label for="aiActionModel" class="form-label">Model *</label>
                        <select class="form-select" id="aiActionModel" required>
                            <option value="">Select a model...</option>
                        </select>
                        <div class="form-text">This model will be used for both creation and execution of the action.</div>
                    </div>

                    <div class="d-grid">
                        <button type="button" class="btn btn-primary btn-lg" onclick="startAICreation()">
                            <i class="bi bi-chat-dots"></i> Start AI-Assisted Creation
                        </button>
                    </div>
                </div>

                <!-- Chat Interface (hidden initially) -->
                <div id="aiCreateChat" class="d-none">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div>
                            <strong id="aiChatActionName"></strong>
                            <br><small class="text-muted" id="aiChatModelName"></small>
                        </div>
                        <span class="badge bg-primary" id="aiChatStatus">In Progress</span>
                    </div>

                    <!-- Chat Messages -->
                    <div id="aiChatMessages" class="border rounded p-3 mb-3" style="height: 350px; overflow-y: auto; background-color: var(--bs-gray-100);">
                        <!-- Messages will be added here dynamically -->
                    </div>

                    <!-- Chat Input -->
                    <div id="aiChatInputArea">
                        <div class="input-group">
                            <input type="text" class="form-control" id="aiChatInput"
                                   placeholder="Type your response..."
                                   onkeypress="handleAIChatKeypress(event)">
                            <button class="btn btn-primary" type="button" onclick="sendAICreationMessage()">
                                <i class="bi bi-send"></i> Send
                            </button>
                        </div>
                    </div>

                    <!-- Completion Message (hidden initially) -->
                    <div id="aiChatComplete" class="d-none">
                        <div class="alert alert-success mb-0">
                            <i class="bi bi-check-circle-fill"></i>
                            Action created successfully!
                            <button type="button" id="viewCreatedAction" class="btn btn-link p-0 align-baseline" onclick="viewCreatedAction();">View action details</button>
                        </div>
                    </div>
                </div>

                <!-- Loading Indicator -->
                <div id="aiCreateLoading" class="d-none text-center py-4">
                    <output class="spinner-border text-primary"></output>
                    <p class="mt-2 text-muted">AI is thinking...</p>
                </div>
            </div>
            <div class="modal-footer" id="aiCreateFooter">
                <button type="button" class="btn btn-secondary" onclick="cancelAICreation()">Cancel</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_scripts %}
<script src="/static/js/actions.js"></script>
<script>
    // Initialise page
    document.addEventListener('DOMContentLoaded', function() {
        loadActions();
        loadRecentRuns();
        loadModels();
        loadTools();
        checkFailedActions();
    });
</script>
{% endblock %}
