// Agent聊天功能
document.addEventListener('DOMContentLoaded', function() {
    const agentInput = document.getElementById('agentInput');
    const sendAgentBtn = document.getElementById('sendAgentBtn');
    const chatHistory = document.getElementById('chatHistory');
    const status = document.getElementById('status');

    // LLM配置相关元素
    const apiUrlInput = document.getElementById('apiUrlInput');
    const apiKeyInput = document.getElementById('apiKeyInput');
    const modelInput = document.getElementById('modelInput');
    const saveConfigBtn = document.getElementById('saveConfigBtn');
    
    // 添加清除缓存按钮
    const clearCacheBtn = document.createElement('button');
    clearCacheBtn.className = 'btn btn-config';
    clearCacheBtn.id = 'clearCacheBtn';
    clearCacheBtn.textContent = '清除缓存';
    saveConfigBtn.parentNode.appendChild(clearCacheBtn);

    // 从本地存储加载配置
    function loadConfigFromLocalStorage() {
        const savedConfig = localStorage.getItem('llmConfig');
        if (savedConfig) {
            try {
                const config = JSON.parse(savedConfig);
                apiUrlInput.value = config.api_url || '';
                apiKeyInput.value = config.api_key || '';
                modelInput.value = config.model || '';
                return true;
            } catch (error) {
                console.log('解析本地存储配置失败:', error);
            }
        }
        return false;
    }

    // 保存配置到本地存储
    function saveConfigToLocalStorage(config) {
        localStorage.setItem('llmConfig', JSON.stringify(config));
    }

    // 清除本地存储
    function clearLocalStorage() {
        localStorage.removeItem('llmConfig');
        apiUrlInput.value = '';
        apiKeyInput.value = '';
        modelInput.value = '';
        status.innerHTML = '<p>缓存已清除</p>';
    }

    // 加载配置
    function loadConfig() {
        // 优先从本地存储加载
        if (!loadConfigFromLocalStorage()) {
            // 如果本地存储没有，从后端加载
            fetch('/agent_config')
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        apiUrlInput.value = data.api_url || '';
                        apiKeyInput.value = data.api_key || '';
                        modelInput.value = data.model || '';
                        // 保存到本地存储
                        saveConfigToLocalStorage({
                            api_url: data.api_url || '',
                            api_key: data.api_key || '',
                            model: data.model || ''
                        });
                    }
                })
                .catch(error => {
                    console.log('加载配置失败:', error);
                    status.innerHTML = `<p>加载配置失败: ${error.message}</p>`;
                });
        }
    }

    // 保存配置
    function saveConfig() {
        const config = {
        api_url: apiUrlInput.value.trim(),
        api_key: apiKeyInput.value.trim(),
        model: modelInput.value.trim()
    };

        console.log('保存配置:', config);
        
        // 保存到本地存储
        saveConfigToLocalStorage(config);
        
        fetch('/agent_config', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(config)
        })
        .then(response => response.json())
        .then(data => {
            console.log('保存配置响应:', data);
            if (data.status === 'success') {
                status.innerHTML = '<p>配置已保存</p>';
            } else {
                status.innerHTML = `<p>配置保存失败: ${data.message}</p>`;
            }
        })
        .catch(error => {
            console.error('配置保存失败:', error);
            status.innerHTML = `<p>配置保存失败: ${error.message}</p>`;
        });
    }

    // 发送消息
    function sendMessage() {
        const text = agentInput.value.trim();
        if (!text) return;

        addMessage('user', text);
        agentInput.value = '';
        status.innerHTML = '<p>处理中...</p>';

        fetch('/agent_chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ text: text })
        })
        .then(response => response.json())
        .then(data => {
            console.log('聊天响应:', data);
            addMessage('agent', data.message || '处理完成');

            // 更新状态
            status.innerHTML = `<p>${data.message || '处理完成'}</p>`;
        })
        .catch(error => {
            console.error('通信错误:', error);
            addMessage('agent', '通信错误，请重试');
            status.innerHTML = `<p>通信错误: ${error.message}</p>`;
        });
    }

    // 添加消息到聊天历史
    function addMessage(type, content) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${type}`;
        messageDiv.innerHTML = `<p>${content}</p>`;
        chatHistory.appendChild(messageDiv);
        chatHistory.scrollTop = chatHistory.scrollHeight;
    }

    // 绑定发送按钮点击事件
    if (sendAgentBtn) {
        sendAgentBtn.addEventListener('click', sendMessage);
    }

    // 绑定回车键发送
    if (agentInput) {
        agentInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendMessage();
            }
        });
    }

    // 绑定保存配置按钮
    if (saveConfigBtn) {
        saveConfigBtn.addEventListener('click', saveConfig);
    }
    
    // 绑定清除缓存按钮
    if (clearCacheBtn) {
        clearCacheBtn.addEventListener('click', clearLocalStorage);
    }

    // 页面加载时获取配置
    loadConfig();
});