// =================== 自动续写功能模块 ===================
// 提供 LaTeX 文档自动续写功能

// =================== 续写设置相关函数 ===================

/**
 * 获取选中的续写模型 - 使用 HTML 中的 selected 属性作为默认值
 * @returns {Promise<string>} 模型名称
 */
async function getSelectedContinueWritingModel() {
    const modelSelectEl = document.getElementById('continue-writing-model-select');
    return modelSelectEl ? modelSelectEl.value : 'doubao-flash';
}

/**
 * 判断续写功能是否开启
 * @returns {Promise<boolean>} 是否开启
 */
async function isContinueWritingEnabled() {
    const enabledSelectEl = document.getElementById('continue-writing-enabled-select');
    if (enabledSelectEl) {
        return enabledSelectEl.value === 'on';
    }
    // Fallback to stored value
    const result = await chrome.storage.sync.get(['continueWritingEnabled']);
    return result.continueWritingEnabled === 'on';
}

/**
 * 获取续写长度设置
 * @returns {Promise<string>} 长度：short/medium/long
 */
async function getContinueWritingLength() {
    const lengthSelectEl = document.getElementById('continue-writing-length-select');
    if (lengthSelectEl) {
        return lengthSelectEl.value;
    }
    // Fallback to stored value
    const result = await chrome.storage.sync.get(['continueWritingLength']);
    return result.continueWritingLength || 'short';
}

/**
 * 获取续写模型的思考程度（自动设为最低档）
 * @param {string} model 模型名称
 * @returns {string} 思考程度参数
 */
function getContinueWritingReasoningEffort(model) {
    // 续写功能直接使用最低档思考程度，节省 token
    if (model === 'doubao-flash') {
        return 'disabled';  // Flash 模型最低档
    }
    if (model === 'doubao-translation' || model === 'doubao-lite') {
        return 'minimal';   // Seed 模型最低档
    }
    if (model === 'gemini-2.5-flash' || model === 'gemini-2.5-flash-lite') {
        return 'none';      // Gemini Flash 模型最低档
    }
    if (model === 'gemini-3-pro') {
        return 'low';       // Gemini Pro 只有 low/high，使用 low
    }
    return 'minimal';       // 默认
}

/**
 * 加载续写模型选择 - 使用 HTML 中的 selected 属性作为默认值
 */
async function loadContinueWritingModelSelection() {
    // 使用 HTML 中的 selected 属性作为默认值
}

/**
 * 保存续写模型选择 - 不再保存到存储
 */
async function saveContinueWritingModelSelection() {
    // 不再保存模型选择
}

/**
 * 加载续写开关设置
 */
async function loadContinueWritingEnabledSelection() {
    try {
        const result = await chrome.storage.sync.get(['continueWritingEnabled']);
        if (result.continueWritingEnabled) {
            const enabledSelectEl = document.getElementById('continue-writing-enabled-select');
            if (enabledSelectEl) {
                enabledSelectEl.value = result.continueWritingEnabled;
            }
        }
    } catch (error) {
        console.error('[ContinueWriting] Error loading enabled selection:', error);
    }
}

/**
 * 保存续写开关设置
 */
async function saveContinueWritingEnabledSelection() {
    const enabledSelectEl = document.getElementById('continue-writing-enabled-select');
    if (enabledSelectEl) {
        try {
            await chrome.storage.sync.set({ continueWritingEnabled: enabledSelectEl.value });
            console.log('[ContinueWriting] Enabled selection saved:', enabledSelectEl.value);

            // 通知 content.js 开关状态变化（转发给 injected.js 更新图标显示）
            notifyContinueWritingEnabledChanged(enabledSelectEl.value === 'on');
        } catch (error) {
            console.error('[ContinueWriting] Error saving enabled selection:', error);
        }
    }
}

/**
 * 通知 content.js 续写开关状态变化
 * @param {boolean} enabled 是否开启
 */
async function notifyContinueWritingEnabledChanged(enabled) {
    try {
        // 获取当前活动标签页
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
        if (tab && tab.id) {
            await chrome.tabs.sendMessage(tab.id, {
                type: 'CONTINUE_WRITING_ENABLED_CHANGED',
                enabled: enabled
            });
            console.log('[ContinueWriting] Notified content.js of enabled change:', enabled);
        }
    } catch (error) {
        console.error('[ContinueWriting] Error notifying content.js:', error);
    }
}

/**
 * 加载续写长度设置
 */
async function loadContinueWritingLengthSelection() {
    try {
        const result = await chrome.storage.sync.get(['continueWritingLength']);
        if (result.continueWritingLength) {
            const lengthSelectEl = document.getElementById('continue-writing-length-select');
            if (lengthSelectEl) {
                lengthSelectEl.value = result.continueWritingLength;
            }
        }
    } catch (error) {
        console.error('[ContinueWriting] Error loading length selection:', error);
    }
}

/**
 * 保存续写长度设置
 */
async function saveContinueWritingLengthSelection() {
    const lengthSelectEl = document.getElementById('continue-writing-length-select');
    if (lengthSelectEl) {
        try {
            await chrome.storage.sync.set({ continueWritingLength: lengthSelectEl.value });
            console.log('[ContinueWriting] Length selection saved:', lengthSelectEl.value);
        } catch (error) {
            console.error('[ContinueWriting] Error saving length selection:', error);
        }
    }
}

/**
 * 初始化续写设置事件监听器
 */
function initContinueWritingSettings() {
    // 加载所有设置
    loadContinueWritingModelSelection();
    loadContinueWritingEnabledSelection();
    loadContinueWritingLengthSelection();

    // 绑定事件监听器
    const modelSelect = document.getElementById('continue-writing-model-select');
    if (modelSelect) {
        modelSelect.addEventListener('change', saveContinueWritingModelSelection);
    }

    const enabledSelect = document.getElementById('continue-writing-enabled-select');
    if (enabledSelect) {
        enabledSelect.addEventListener('change', saveContinueWritingEnabledSelection);
    }

    const lengthSelect = document.getElementById('continue-writing-length-select');
    if (lengthSelect) {
        lengthSelect.addEventListener('change', saveContinueWritingLengthSelection);
    }

    console.log('[ContinueWriting] Settings initialized');
}

// =================== 续写核心功能 ===================

// 续写状态
let continueWritingInProgress = false;
let continueWritingDebounceTimer = null;
const CONTINUE_WRITING_DEBOUNCE_MS = 2000;  // 用户停止输入 2 秒后触发续写

/**
 * 调用后端续写 API
 * @param {string} content 文档内容（光标之前的内容）
 * @param {string} model 模型名称
 * @param {string} length 续写长度
 * @returns {Promise<object>} 续写结果
 */
async function callContinueWritingAPI(content, model, length) {
    const reasoningEffort = getContinueWritingReasoningEffort(model);

    console.log('[ContinueWriting] Calling API, model:', model, 'length:', length, 'reasoning_effort:', reasoningEffort);

    const response = await fetch(`${BACKEND_API_URL}/api/continue-writing`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        credentials: 'include',
        body: JSON.stringify({
            content: content,
            model: model,
            reasoning_effort: reasoningEffort,
            length: length
        })
    });

    if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.detail || `续写请求失败: ${response.status}`);
    }

    return await response.json();
}

/**
 * 触发自动续写
 * 在用户停止输入一段时间后调用
 * @param {string} contentBeforeCursor 光标之前的文档内容
 * @param {function} onSuccess 成功回调，接收续写内容
 * @param {function} onError 错误回调
 */
async function triggerContinueWriting(contentBeforeCursor, onSuccess, onError) {
    // 检查是否启用
    const enabled = await isContinueWritingEnabled();
    if (!enabled) {
        console.log('[ContinueWriting] Disabled, skipping');
        return;
    }

    // 检查是否正在进行中
    if (continueWritingInProgress) {
        console.log('[ContinueWriting] Already in progress, skipping');
        return;
    }

    // 检查内容是否有效
    if (!contentBeforeCursor || contentBeforeCursor.trim().length < 50) {
        console.log('[ContinueWriting] Content too short, skipping');
        return;
    }

    try {
        continueWritingInProgress = true;

        const model = await getSelectedContinueWritingModel();
        const length = await getContinueWritingLength();

        console.log('[ContinueWriting] Starting, model:', model, 'length:', length);

        const result = await callContinueWritingAPI(contentBeforeCursor, model, length);

        if (result.success && result.continuation) {
            console.log('[ContinueWriting] Success, continuation length:', result.continuation.length);
            if (onSuccess) {
                onSuccess(result.continuation, result);
            }

            // 更新用户 token 显示
            if (result.remaining_tokens !== undefined && typeof updateUserTokensDisplay === 'function') {
                updateUserTokensDisplay(result.remaining_tokens);
            }
        } else {
            throw new Error(result.error || '续写返回空内容');
        }

    } catch (error) {
        console.error('[ContinueWriting] Error:', error);
        if (onError) {
            onError(error);
        }
    } finally {
        continueWritingInProgress = false;
    }
}

/**
 * 防抖触发续写
 * @param {string} contentBeforeCursor 光标之前的文档内容
 * @param {function} onSuccess 成功回调
 * @param {function} onError 错误回调
 */
function debouncedTriggerContinueWriting(contentBeforeCursor, onSuccess, onError) {
    // 清除之前的定时器
    if (continueWritingDebounceTimer) {
        clearTimeout(continueWritingDebounceTimer);
    }

    // 设置新的定时器
    continueWritingDebounceTimer = setTimeout(() => {
        triggerContinueWriting(contentBeforeCursor, onSuccess, onError);
    }, CONTINUE_WRITING_DEBOUNCE_MS);
}

/**
 * 取消待执行的续写
 */
function cancelPendingContinueWriting() {
    if (continueWritingDebounceTimer) {
        clearTimeout(continueWritingDebounceTimer);
        continueWritingDebounceTimer = null;
    }
}

// 导出函数（供 sidepanel.js 使用）
// 在模块化环境中可以使用 export，这里通过全局函数暴露
console.log('[ContinueWriting] Module loaded');
