<!--
Copyright (C) 2026 Stefy Lanza <stefy@nexlab.net>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
-->
{% extends "base.html" %}

{% block title %}Settings - AISBF Dashboard{% endblock %}

{% block content %}
<h2 style="margin-bottom: 30px;">Server Settings</h2>

{% if success %}
<div class="alert alert-success">{{ success }}</div>
{% endif %}

{% if error %}
<div class="alert alert-error">{{ error }}</div>
{% endif %}

<form method="POST">
    <h3 style="margin-bottom: 20px;">Server Configuration</h3>
    
    <div class="form-group">
        <label for="host">Host</label>
        <input type="text" id="host" name="host" value="{{ config.server.host }}" required>
    </div>
    
    <div class="form-group">
        <label for="port">Port</label>
        <input type="number" id="port" name="port" value="{{ config.server.port }}" required>
    </div>
    
    <div class="form-group">
        <label for="protocol">Protocol</label>
        <select id="protocol" name="protocol" onchange="toggleSSLFields()">
            <option value="http" {% if config.server.protocol == 'http' %}selected{% endif %}>HTTP</option>
            <option value="https" {% if config.server.protocol == 'https' %}selected{% endif %}>HTTPS</option>
        </select>
    </div>
    
    <div id="ssl-fields" style="display: {% if config.server.protocol == 'https' %}block{% else %}none{% endif %};">
        <div class="form-group">
            <label for="public_domain">Public Domain (for Let's Encrypt)</label>
            <input type="text" id="public_domain" name="public_domain" value="{{ config.server.public_domain or '' }}" placeholder="example.com (optional)">
            <small style="color: #666; display: block; margin-top: 5px;">If specified, Let's Encrypt will be used to generate valid SSL certificates. Leave empty to use self-signed certificates.</small>
        </div>
        
        <div class="form-group">
            <label for="ssl_cert">SSL Certificate Path</label>
            <input type="text" id="ssl_cert" name="ssl_cert" value="{{ config.server.ssl_cert or '' }}" placeholder="~/.aisbf/cert.pem (default)">
            <small style="color: #666; display: block; margin-top: 5px;">Path to SSL certificate file. Leave empty to use default (~/.aisbf/cert.pem). Auto-generated using Let's Encrypt if public domain is set, otherwise self-signed.</small>
        </div>
        
        <div class="form-group">
            <label for="ssl_key">SSL Key Path</label>
            <input type="text" id="ssl_key" name="ssl_key" value="{{ config.server.ssl_key or '' }}" placeholder="~/.aisbf/key.pem (default)">
            <small style="color: #666; display: block; margin-top: 5px;">Path to SSL private key file. Leave empty to use default (~/.aisbf/key.pem). Auto-generated with certificate.</small>
        </div>
    </div>
    
    <h3 style="margin: 30px 0 20px;">Authentication</h3>
    
    <div class="form-group">
        <label>
            <input type="checkbox" name="auth_enabled" {% if config.auth.enabled %}checked{% endif %}>
            Enable API Authentication
        </label>
    </div>
    
    <div class="form-group">
        <label for="auth_tokens">Auth Tokens (one per line)</label>
        <textarea id="auth_tokens" name="auth_tokens" style="min-height: 100px;">{{ '\n'.join(config.auth.tokens) }}</textarea>
    </div>
    
    <h3 style="margin: 30px 0 20px;">MCP Server</h3>
    
    <div class="form-group">
        <label>
            <input type="checkbox" name="mcp_enabled" {% if config.mcp.enabled %}checked{% endif %}>
            Enable MCP Server
        </label>
        <small style="color: #666; display: block; margin-top: 5px;">Model Context Protocol server for remote agent configuration</small>
    </div>
    
    <div class="form-group">
        <label for="autoselect_tokens">Autoselect Tokens (one per line)</label>
        <textarea id="autoselect_tokens" name="autoselect_tokens" style="min-height: 80px;" placeholder="Tokens for autoselection/autorotation access">{{ '\n'.join(config.mcp.autoselect_tokens) if config.mcp.autoselect_tokens else '' }}</textarea>
        <small style="color: #666; display: block; margin-top: 5px;">Tokens that give access to autoselection and autorotation settings + standard APIs</small>
    </div>
    
    <div class="form-group">
        <label for="fullconfig_tokens">Full Config Tokens (one per line)</label>
        <textarea id="fullconfig_tokens" name="fullconfig_tokens" style="min-height: 80px;" placeholder="Tokens for full configuration access">{{ '\n'.join(config.mcp.fullconfig_tokens) if config.mcp.fullconfig_tokens else '' }}</textarea>
        <small style="color: #666; display: block; margin-top: 5px;">Tokens that give access to full system configuration + standard APIs</small>
    </div>
    
    <h3 style="margin: 30px 0 20px;">Dashboard</h3>
    
    <div class="form-group">
        <label for="dashboard_username">Dashboard Username</label>
        <input type="text" id="dashboard_username" name="dashboard_username" value="{{ config.dashboard.username }}" required>
    </div>
    
    <div class="form-group">
        <label for="dashboard_password">Dashboard Password</label>
        <input type="password" id="dashboard_password" name="dashboard_password" placeholder="Leave blank to keep current">
    </div>
    
    <h3 style="margin: 30px 0 20px;">Internal Models</h3>
    
    <div class="form-group">
        <label for="condensation_model_id">Condensation Model ID</label>
        <input type="text" id="condensation_model_id" name="condensation_model_id" value="{{ config.internal_model.condensation_model_id }}" required>
        <small style="color: #666; display: block; margin-top: 5px;">Used when condensation model is set to "internal"</small>
    </div>
    
    <div class="form-group">
        <label for="autoselect_model_id">Autoselect Model ID</label>
        <input type="text" id="autoselect_model_id" name="autoselect_model_id" value="{{ config.internal_model.autoselect_model_id }}" required>
        <small style="color: #666; display: block; margin-top: 5px;">Used when autoselect selection_model is set to "internal"</small>
    </div>
    
    <div class="form-group">
        <label for="nsfw_classifier">NSFW Classifier Model ID</label>
        <input type="text" id="nsfw_classifier" name="nsfw_classifier" value="{{ config.internal_model.nsfw_classifier or 'michelleli99/NSFW_text_classifier' }}" required>
        <small style="color: #666; display: block; margin-top: 5px;">Model used for NSFW content detection</small>
    </div>
    
    <div class="form-group">
        <label for="privacy_classifier">Privacy Classifier Model ID</label>
        <input type="text" id="privacy_classifier" name="privacy_classifier" value="{{ config.internal_model.privacy_classifier or 'iiiorg/piiranha-v1-detect-personal-information' }}" required>
        <small style="color: #666; display: block; margin-top: 5px;">Model used for privacy-sensitive information detection</small>
    </div>
    
    <div class="form-group">
        <label for="semantic_vectorization">Semantic Vectorization Model ID</label>
        <input type="text" id="semantic_vectorization" name="semantic_vectorization" value="{{ config.internal_model.semantic_vectorization or 'sentence-transformers/all-MiniLM-L6-v2' }}" required>
        <small style="color: #666; display: block; margin-top: 5px;">Model used for semantic embedding and vectorization</small>
    </div>
    
    <h3 style="margin: 30px 0 20px;">Database Configuration</h3>

    <div class="form-group">
        <label for="database_type">Database Type</label>
        <select id="database_type" name="database_type" onchange="toggleDatabaseFields()">
            <option value="sqlite" {% if config.database and config.database.type == 'sqlite' %}selected{% endif %}>SQLite</option>
            <option value="mysql" {% if config.database and config.database.type == 'mysql' %}selected{% endif %}>MySQL</option>
        </select>
        <small style="color: #666; display: block; margin-top: 5px;">Choose the database backend (SQLite is recommended for most users)</small>
    </div>

    <div id="sqlite-fields" style="display: {% if not config.database or config.database.type == 'sqlite' %}block{% else %}none{% endif %};">
        <div class="form-group">
            <label for="sqlite_path">SQLite Database Path</label>
            <input type="text" id="sqlite_path" name="sqlite_path" value="{{ config.database.sqlite_path if config.database and config.database.sqlite_path else '~/.aisbf/aisbf.db' }}">
            <small style="color: #666; display: block; margin-top: 5px;">Path to SQLite database file (supports ~ expansion)</small>
        </div>
    </div>

    <div id="mysql-fields" style="display: {% if config.database and config.database.type == 'mysql' %}block{% else %}none{% endif %};">
        <div class="form-group">
            <label for="mysql_host">MySQL Host</label>
            <input type="text" id="mysql_host" name="mysql_host" value="{{ config.database.mysql_host if config.database and config.database.mysql_host else 'localhost' }}">
            <small style="color: #666; display: block; margin-top: 5px;">MySQL server hostname or IP address</small>
        </div>

        <div class="form-group">
            <label for="mysql_port">MySQL Port</label>
            <input type="number" id="mysql_port" name="mysql_port" value="{{ config.database.mysql_port if config.database and config.database.mysql_port else 3306 }}">
            <small style="color: #666; display: block; margin-top: 5px;">MySQL server port (default: 3306)</small>
        </div>

        <div class="form-group">
            <label for="mysql_user">MySQL Username</label>
            <input type="text" id="mysql_user" name="mysql_user" value="{{ config.database.mysql_user if config.database and config.database.mysql_user else 'aisbf' }}">
            <small style="color: #666; display: block; margin-top: 5px;">MySQL database username</small>
        </div>

        <div class="form-group">
            <label for="mysql_password">MySQL Password</label>
            <input type="password" id="mysql_password" name="mysql_password" placeholder="Leave blank to keep current">
            <small style="color: #666; display: block; margin-top: 5px;">MySQL database password</small>
        </div>

        <div class="form-group">
            <label for="mysql_database">MySQL Database Name</label>
            <input type="text" id="mysql_database" name="mysql_database" value="{{ config.database.mysql_database if config.database and config.database.mysql_database else 'aisbf' }}">
            <small style="color: #666; display: block; margin-top: 5px;">MySQL database name</small>
        </div>
    </div>

    <h3 style="margin: 30px 0 20px;">Cache Configuration</h3>

    <div class="form-group">
        <label for="cache_type">Cache Type</label>
        <select id="cache_type" name="cache_type" onchange="toggleCacheFields()">
            <option value="sqlite" {% if config.cache and config.cache.type == 'sqlite' %}selected{% endif %}>SQLite</option>
            <option value="mysql" {% if config.cache and config.cache.type == 'mysql' %}selected{% endif %}>MySQL</option>
            <option value="redis" {% if config.cache and config.cache.type == 'redis' %}selected{% endif %}>Redis</option>
            <option value="file" {% if config.cache and config.cache.type == 'file' %}selected{% endif %}>File-based</option>
            <option value="memory" {% if not config.cache or config.cache.type == 'memory' %}selected{% endif %}>Memory</option>
        </select>
        <small style="color: #666; display: block; margin-top: 5px;">Choose the cache backend for model embeddings and other cached data (SQLite recommended for most users)</small>
    </div>

    <div id="sqlite-cache-fields" style="display: {% if config.cache and config.cache.type == 'sqlite' %}block{% else %}none{% endif %};">
        <div class="form-group">
            <label for="sqlite_path">SQLite Cache Path</label>
            <input type="text" id="sqlite_path" name="sqlite_path" value="{{ config.cache.sqlite_path if config.cache and config.cache.sqlite_path else '~/.aisbf/cache.db' }}">
            <small style="color: #666; display: block; margin-top: 5px;">Path to SQLite cache database file (supports ~ expansion)</small>
        </div>
    </div>

    <div id="mysql-cache-fields" style="display: {% if config.cache and config.cache.type == 'mysql' %}block{% else %}none{% endif %};">
        <div class="form-group">
            <label for="mysql_cache_host">MySQL Host</label>
            <input type="text" id="mysql_cache_host" name="mysql_cache_host" value="{{ config.cache.mysql_host if config.cache and config.cache.mysql_host else 'localhost' }}">
            <small style="color: #666; display: block; margin-top: 5px;">MySQL server hostname or IP address</small>
        </div>

        <div class="form-group">
            <label for="mysql_cache_port">MySQL Port</label>
            <input type="number" id="mysql_cache_port" name="mysql_cache_port" value="{{ config.cache.mysql_port if config.cache and config.cache.mysql_port else 3306 }}">
            <small style="color: #666; display: block; margin-top: 5px;">MySQL server port (default: 3306)</small>
        </div>

        <div class="form-group">
            <label for="mysql_cache_user">MySQL Username</label>
            <input type="text" id="mysql_cache_user" name="mysql_cache_user" value="{{ config.cache.mysql_user if config.cache and config.cache.mysql_user else 'aisbf' }}">
            <small style="color: #666; display: block; margin-top: 5px;">MySQL database username</small>
        </div>

        <div class="form-group">
            <label for="mysql_cache_password">MySQL Password</label>
            <input type="password" id="mysql_cache_password" name="mysql_cache_password" placeholder="Leave blank to keep current">
            <small style="color: #666; display: block; margin-top: 5px;">MySQL database password</small>
        </div>

        <div class="form-group">
            <label for="mysql_cache_database">MySQL Database Name</label>
            <input type="text" id="mysql_cache_database" name="mysql_cache_database" value="{{ config.cache.mysql_database if config.cache and config.cache.mysql_database else 'aisbf_cache' }}">
            <small style="color: #666; display: block; margin-top: 5px;">MySQL database name for cache</small>
        </div>
    </div>

    <div id="redis-cache-fields" style="display: {% if config.cache and config.cache.type == 'redis' %}block{% else %}none{% endif %};">
        <div class="form-group">
            <label for="redis_host">Redis Host</label>
            <input type="text" id="redis_host" name="redis_host" value="{{ config.cache.redis_host if config.cache and config.cache.redis_host else 'localhost' }}">
            <small style="color: #666; display: block; margin-top: 5px;">Redis server hostname or IP address</small>
        </div>

        <div class="form-group">
            <label for="redis_port">Redis Port</label>
            <input type="number" id="redis_port" name="redis_port" value="{{ config.cache.redis_port if config.cache and config.cache.redis_port else 6379 }}">
            <small style="color: #666; display: block; margin-top: 5px;">Redis server port (default: 6379)</small>
        </div>

        <div class="form-group">
            <label for="redis_db">Redis Database</label>
            <input type="number" id="redis_db" name="redis_db" value="{{ config.cache.redis_db if config.cache and config.cache.redis_db else 0 }}">
            <small style="color: #666; display: block; margin-top: 5px;">Redis database number (default: 0)</small>
        </div>

        <div class="form-group">
            <label for="redis_password">Redis Password</label>
            <input type="password" id="redis_password" name="redis_password" placeholder="Leave blank if no password">
            <small style="color: #666; display: block; margin-top: 5px;">Redis password (optional)</small>
        </div>

        <div class="form-group">
            <label for="redis_key_prefix">Redis Key Prefix</label>
            <input type="text" id="redis_key_prefix" name="redis_key_prefix" value="{{ config.cache.redis_key_prefix if config.cache and config.cache.redis_key_prefix else 'aisbf:' }}">
            <small style="color: #666; display: block; margin-top: 5px;">Prefix for Redis keys (default: aisbf:)</small>
        </div>
    </div>

    <h3 style="margin: 30px 0 20px;">Response Cache Statistics</h3>
    
    <div id="cache-stats" style="margin-bottom: 20px; padding: 15px; background: #0f3460; border-radius: 6px; border-left: 4px solid #16213e;">
        <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 10px;">
            <strong>Status:</strong>
            <span id="cache-stats-text" style="color: #666;">Loading...</span>
        </div>
        <div id="cache-stats-details" style="display: none; margin-top: 10px;">
            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px;">
                <div style="background: #16213e; padding: 10px; border-radius: 4px;">
                    <div style="color: #666; font-size: 0.9em;">Hits</div>
                    <div id="cache-hits" style="font-size: 1.2em; font-weight: bold; color: #4caf50;">0</div>
                </div>
                <div style="background: #16213e; padding: 10px; border-radius: 4px;">
                    <div style="color: #666; font-size: 0.9em;">Misses</div>
                    <div id="cache-misses" style="font-size: 1.2em; font-weight: bold; color: #ff9800;">0</div>
                </div>
                <div style="background: #16213e; padding: 10px; border-radius: 4px;">
                    <div style="color: #666; font-size: 0.9em;">Hit Rate</div>
                    <div id="cache-hit-rate" style="font-size: 1.2em; font-weight: bold; color: #2196f3;">0%</div>
                </div>
                <div style="background: #16213e; padding: 10px; border-radius: 4px;">
                    <div style="color: #666; font-size: 0.9em;">Size</div>
                    <div id="cache-size" style="font-size: 1.2em; font-weight: bold; color: #9c27b0;">0</div>
                </div>
                <div style="background: #16213e; padding: 10px; border-radius: 4px;">
                    <div style="color: #666; font-size: 0.9em;">Evictions</div>
                    <div id="cache-evictions" style="font-size: 1.2em; font-weight: bold; color: #f44336;">0</div>
                </div>
                <div style="background: #16213e; padding: 10px; border-radius: 4px;">
                    <div style="color: #666; font-size: 0.9em;">Backend</div>
                    <div id="cache-backend" style="font-size: 1.2em; font-weight: bold; color: #00bcd4;">-</div>
                </div>
            </div>
            <div style="margin-top: 10px;">
                <button type="button" onclick="clearResponseCache()" class="btn btn-secondary" style="background: #f44336; color: white; border: none; padding: 8px 16px; border-radius: 4px; cursor: pointer;">Clear Cache</button>
                <button type="button" onclick="refreshCacheStats()" class="btn btn-secondary" style="margin-left: 10px; padding: 8px 16px; border-radius: 4px; cursor: pointer;">Refresh</button>
            </div>
        </div>
    </div>

    <h3 style="margin: 30px 0 20px;">Content Classification</h3>

    <div class="form-group">
        <label>
            <input type="checkbox" name="classify_nsfw" {% if config.classify_nsfw %}checked{% endif %}>
            Enable NSFW Classification
        </label>
        <small style="color: #666; display: block; margin-top: 5px;">Enable automatic NSFW content detection for model selection</small>
    </div>

    <div class="form-group">
        <label>
            <input type="checkbox" name="classify_privacy" {% if config.classify_privacy %}checked{% endif %}>
            Enable Privacy Classification
        </label>
        <small style="color: #666; display: block; margin-top: 5px;">Enable automatic privacy-sensitive content detection for model selection</small>
    </div>

    <div class="form-group">
        <label>
            <input type="checkbox" name="classify_semantic" {% if config.classify_semantic %}checked{% endif %}>
            Enable Semantic Classification
        </label>
        <small style="color: #666; display: block; margin-top: 5px;">Enable semantic content classification using the configured model</small>
    </div>
    
    <h3 style="margin: 30px 0 20px;">TOR Hidden Service</h3>
    
    <div id="tor-status" style="margin-bottom: 20px; padding: 15px; background: #0f3460; border-radius: 6px; border-left: 4px solid #16213e;">
        <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 10px;">
            <strong>Status:</strong>
            <span id="tor-status-text" style="color: #666;">Loading...</span>
        </div>
        <div id="tor-onion-address" style="display: none; margin-top: 10px;">
            <strong>Onion Address:</strong>
            <code id="tor-onion-value" style="background: #16213e; padding: 5px 10px; border-radius: 4px; display: inline-block; margin-left: 10px;"></code>
        </div>
    </div>
    
    <div class="form-group">
        <label>
            <input type="checkbox" name="tor_enabled" id="tor_enabled" {% if config.tor and config.tor.enabled %}checked{% endif %} onchange="toggleTorFields()">
            Enable TOR Hidden Service
        </label>
        <small style="color: #666; display: block; margin-top: 5px;">Expose AISBF over TOR network as a hidden service</small>
    </div>
    
    <div id="tor-fields" style="display: {% if config.tor and config.tor.enabled %}block{% else %}none{% endif %};">
        <div class="form-group">
            <label for="tor_control_host">TOR Control Host</label>
            <input type="text" id="tor_control_host" name="tor_control_host" value="{{ config.tor.control_host if config.tor else '127.0.0.1' }}">
            <small style="color: #666; display: block; margin-top: 5px;">TOR control port host (default: 127.0.0.1)</small>
        </div>
        
        <div class="form-group">
            <label for="tor_control_port">TOR Control Port</label>
            <input type="number" id="tor_control_port" name="tor_control_port" value="{{ config.tor.control_port if config.tor else 9051 }}">
            <small style="color: #666; display: block; margin-top: 5px;">TOR control port (default: 9051)</small>
        </div>
        
        <div class="form-group">
            <label for="tor_control_password">TOR Control Password</label>
            <input type="password" id="tor_control_password" name="tor_control_password" value="{{ config.tor.control_password if config.tor and config.tor.control_password else '' }}" placeholder="Leave blank if no password">
            <small style="color: #666; display: block; margin-top: 5px;">Password for TOR control port authentication (optional)</small>
        </div>
        
        <div class="form-group">
            <label for="tor_hidden_service_dir">Hidden Service Directory</label>
            <div style="display: flex; gap: 10px; align-items: flex-start;">
                <input type="text" id="tor_hidden_service_dir" name="tor_hidden_service_dir" value="{{ config.tor.hidden_service_dir if config.tor and config.tor.hidden_service_dir else '' }}" placeholder="Leave blank for ephemeral service" style="flex: 1;">
                <button type="button" onclick="createPersistentService()" class="btn btn-secondary" style="white-space: nowrap;">Create Persistent</button>
            </div>
            <small style="color: #666; display: block; margin-top: 5px;">Directory for persistent hidden service. Leave blank for ephemeral (temporary) service. Click "Create Persistent" to use default directory.</small>
        </div>
        
        <div class="form-group">
            <label for="tor_hidden_service_port">Hidden Service Port</label>
            <input type="number" id="tor_hidden_service_port" name="tor_hidden_service_port" value="{{ config.tor.hidden_service_port if config.tor else 80 }}">
            <small style="color: #666; display: block; margin-top: 5px;">Port exposed on the hidden service (default: 80)</small>
        </div>
        
        <div class="form-group">
            <label for="tor_socks_host">SOCKS Proxy Host</label>
            <input type="text" id="tor_socks_host" name="tor_socks_host" value="{{ config.tor.socks_host if config.tor else '127.0.0.1' }}">
            <small style="color: #666; display: block; margin-top: 5px;">TOR SOCKS proxy host (default: 127.0.0.1)</small>
        </div>
        
        <div class="form-group">
            <label for="tor_socks_port">SOCKS Proxy Port</label>
            <input type="number" id="tor_socks_port" name="tor_socks_port" value="{{ config.tor.socks_port if config.tor else 9050 }}">
            <small style="color: #666; display: block; margin-top: 5px;">TOR SOCKS proxy port (default: 9050)</small>
        </div>
    </div>
    
    <div style="display: flex; gap: 10px; margin-top: 30px;">
        <button type="submit" class="btn">Save Settings</button>
        <a href="{{ url_for(request, '/dashboard') }}" class="btn btn-secondary">Cancel</a>
    </div>
</form>

<script>
function toggleSSLFields() {
    const protocol = document.getElementById('protocol').value;
    const sslFields = document.getElementById('ssl-fields');
    
    if (protocol === 'https') {
        sslFields.style.display = 'block';
    } else {
        sslFields.style.display = 'none';
    }
}

function toggleTorFields() {
    const torEnabled = document.getElementById('tor_enabled').checked;
    const torFields = document.getElementById('tor-fields');

    if (torEnabled) {
        torFields.style.display = 'block';
    } else {
        torFields.style.display = 'none';
    }
}

function toggleDatabaseFields() {
    const dbType = document.getElementById('database_type').value;
    const sqliteFields = document.getElementById('sqlite-fields');
    const mysqlFields = document.getElementById('mysql-fields');

    if (dbType === 'sqlite') {
        sqliteFields.style.display = 'block';
        mysqlFields.style.display = 'none';
    } else if (dbType === 'mysql') {
        sqliteFields.style.display = 'none';
        mysqlFields.style.display = 'block';
    }
}

function toggleCacheFields() {
    const cacheType = document.getElementById('cache_type').value;
    const redisFields = document.getElementById('redis-cache-fields');
    const sqliteFields = document.getElementById('sqlite-cache-fields');
    const mysqlCacheFields = document.getElementById('mysql-cache-fields');

    // Hide all cache-specific fields first
    redisFields.style.display = 'none';
    sqliteFields.style.display = 'none';
    mysqlCacheFields.style.display = 'none';

    // Show only the relevant fields
    if (cacheType === 'redis') {
        redisFields.style.display = 'block';
    } else if (cacheType === 'sqlite') {
        sqliteFields.style.display = 'block';
    } else if (cacheType === 'mysql') {
        mysqlCacheFields.style.display = 'block';
    }
}

function createPersistentService() {
    const dirInput = document.getElementById('tor_hidden_service_dir');
    const defaultDir = '~/.aisbf/tor_hidden_service';
    
    if (dirInput.value && dirInput.value.trim() !== '') {
        if (!confirm('This will replace the current directory path. Continue?')) {
            return;
        }
    }
    
    dirInput.value = defaultDir;
    dirInput.focus();
    
    // Visual feedback
    dirInput.style.backgroundColor = '#1a4d2e';
    setTimeout(() => {
        dirInput.style.backgroundColor = '';
    }, 500);
}

async function checkTorStatus() {
    try {
        const response = await fetch('{{ url_for(request, "/dashboard/tor/status") }}');
        const status = await response.json();
        
        const statusText = document.getElementById('tor-status-text');
        const onionAddressDiv = document.getElementById('tor-onion-address');
        const onionValue = document.getElementById('tor-onion-value');
        
        if (status.enabled && status.connected && status.onion_address) {
            statusText.textContent = 'Active';
            statusText.style.color = '#4caf50';
            onionAddressDiv.style.display = 'block';
            onionValue.textContent = status.onion_address;
        } else if (status.enabled && !status.connected) {
            statusText.textContent = 'Enabled but not connected';
            statusText.style.color = '#ff9800';
            onionAddressDiv.style.display = 'none';
        } else {
            statusText.textContent = 'Disabled';
            statusText.style.color = '#666';
            onionAddressDiv.style.display = 'none';
        }
    } catch (error) {
        console.error('Error checking TOR status:', error);
        document.getElementById('tor-status-text').textContent = 'Error checking status';
        document.getElementById('tor-status-text').style.color = '#f44336';
    }
}

// Check TOR status on page load
document.addEventListener('DOMContentLoaded', function() {
    checkTorStatus();
    // Refresh status every 30 seconds
    setInterval(checkTorStatus, 30000);
    
    // Load cache statistics
    refreshCacheStats();
    // Refresh cache stats every 10 seconds
    setInterval(refreshCacheStats, 10000);
});

async function refreshCacheStats() {
    try {
        const response = await fetch('{{ url_for(request, "/dashboard/response-cache/stats") }}');
        const data = await response.json();
        
        const statsText = document.getElementById('cache-stats-text');
        const statsDetails = document.getElementById('cache-stats-details');
        
        if (data.enabled) {
            statsText.textContent = 'Enabled';
            statsText.style.color = '#4caf50';
            statsDetails.style.display = 'block';
            
            document.getElementById('cache-hits').textContent = data.hits || 0;
            document.getElementById('cache-misses').textContent = data.misses || 0;
            document.getElementById('cache-hit-rate').textContent = (data.hit_rate || 0).toFixed(1) + '%';
            document.getElementById('cache-size').textContent = data.size || 0;
            document.getElementById('cache-evictions').textContent = data.evictions || 0;
            document.getElementById('cache-backend').textContent = data.backend || '-';
        } else {
            statsText.textContent = 'Disabled';
            statsText.style.color = '#666';
            statsDetails.style.display = 'none';
        }
    } catch (error) {
        console.error('Error fetching cache stats:', error);
        document.getElementById('cache-stats-text').textContent = 'Error loading stats';
        document.getElementById('cache-stats-text').style.color = '#f44336';
    }
}

async function clearResponseCache() {
    if (!confirm('Are you sure you want to clear the response cache? This will remove all cached responses.')) {
        return;
    }
    
    try {
        const response = await fetch('{{ url_for(request, "/dashboard/response-cache/clear") }}', {
            method: 'POST'
        });
        const data = await response.json();
        
        if (data.success) {
            alert('Response cache cleared successfully');
            refreshCacheStats();
        } else {
            alert('Failed to clear cache: ' + (data.error || 'Unknown error'));
        }
    } catch (error) {
        console.error('Error clearing cache:', error);
        alert('Error clearing cache: ' + error.message);
    }
}
</script>
{% endblock %}
