// Translation module for Overleaf Chrome Extension
// 全文翻译功能：微软翻译、豆包翻译、反向翻译

// Translate full document using Microsoft Translator
async function translateFullDocumentWithMicrosoft(projectId) {
    console.log('[MS Full Translate] Starting full document translation...');

    try {
        // Split content into chunks (lines)
        const lines = currentContent.split('\n');
        console.log('[MS Full Translate] Total lines:', lines.length);

        // Microsoft Translator supports up to 50,000 characters per request
        // We'll use 10,000 characters per chunk to be safe
        const MAX_CHUNK_SIZE = 10000;
        const chunks = [];
        let currentChunk = [];
        let currentChunkSize = 0;

        for (let i = 0; i < lines.length; i++) {
            const line = lines[i];
            const lineSize = line.length + 1; // +1 for newline

            if (currentChunkSize + lineSize > MAX_CHUNK_SIZE && currentChunk.length > 0) {
                // Save current chunk and start new one
                chunks.push(currentChunk.join('\n'));
                currentChunk = [line];
                currentChunkSize = lineSize;
            } else {
                currentChunk.push(line);
                currentChunkSize += lineSize;
            }
        }

        // Add last chunk
        if (currentChunk.length > 0) {
            chunks.push(currentChunk.join('\n'));
        }

        console.log('[MS Full Translate] Split into', chunks.length, 'chunks');

        // Translate each chunk
        let translatedContent = '';
        for (let i = 0; i < chunks.length; i++) {
            const progress = Math.round(((i + 1) / chunks.length) * 100);
            document.getElementById('progress-text').textContent = `翻译进度: ${progress}% (${i + 1}/${chunks.length})`;
            document.getElementById('progress-bar').style.width = `${progress}%`;

            console.log(`[MS Full Translate] Translating chunk ${i + 1}/${chunks.length}...`);

            const translatedChunk = await microsoftTranslator.translate(chunks[i], 'en', 'zh-Hans');
            translatedContent += translatedChunk;

            if (i < chunks.length - 1) {
                translatedContent += '\n';
            }

            // Update preview every few chunks
            if (i % 3 === 0 || i === chunks.length - 1) {
                renderZhDocument(translatedContent);
                document.getElementById('zh-content-length').textContent = translatedContent.length.toString();
            }
        }

        console.log('[MS Full Translate] Translation completed');

        // Save to local storage
        const saved = await localDocStorage.save(projectId, currentFileName, translatedContent);

        if (saved) {
            showSuccess('翻译完成！已保存到本地存储');
        } else {
            showError('翻译完成，但保存到本地存储失败');
        }

        // 隐藏进度条
        setTimeout(() => {
            document.getElementById('translation-progress').style.display = 'none';
        }, 1500);

    } finally {
        document.getElementById('full-translate-btn').disabled = false;
    }
}

// Translate full document using Doubao Translation API (豆包翻译)
// 基于行号的翻译，保持原文档行结构，支持本地存储
async function translateFullDocumentWithDoubao(projectId, model = 'doubao-translation') {
    // 获取思考程度选择
    const reasoningEffort = await getSelectedReasoningEffort();
    console.log('[Doubao Full Translate] Starting full document translation, model:', model, ', reasoningEffort:', reasoningEffort);

    try {
        // 配置参数
        const MAX_CHUNK_SIZE = 4000;  // 每个请求块的最大字符数
        const PARALLEL_REQUESTS = 20;  // 并行请求数量
        const MIN_LINE_LENGTH = 7;     // 最小行长度阈值，小于此值的行跳过翻译

        // 将文档按行分割
        const allLines = currentContent.split('\n');
        const totalLines = allLines.length;
        console.log('[Doubao Full Translate] Total lines:', totalLines);

        // === 步骤1: 初始化中文文档（复制原文） ===
        console.log('[Doubao Full Translate] Saving with projectId:', projectId, 'fileName:', currentFileName);
        const initSaved = await localDocStorage.save(projectId, currentFileName, currentContent);
        console.log('[Doubao Full Translate] Document initialized:', initSaved);

        // 创建内存中的翻译结果数组
        const translatedLines = [...allLines];

        // 分离需要翻译的行和跳过的行
        const linesToTranslate = {};  // {行号: 内容}
        const skippedLines = {};      // {行号: 内容}
        let totalCharsToTranslate = 0;

        for (let i = 0; i < allLines.length; i++) {
            const line = allLines[i];
            const lineNum = String(i + 1);  // 行号从1开始
            const trimmedLine = line.trim();

            if (trimmedLine.length < MIN_LINE_LENGTH) {
                // 跳过短行，直接保留原内容
                skippedLines[lineNum] = line;
            } else {
                linesToTranslate[lineNum] = line;
                totalCharsToTranslate += line.length;
            }
        }

        const toTranslateCount = Object.keys(linesToTranslate).length;
        const skippedCount = Object.keys(skippedLines).length;
        console.log(`[Doubao Full Translate] Lines to translate: ${toTranslateCount}, Skipped lines: ${skippedCount}`);
        console.log(`[Doubao Full Translate] Total characters to translate: ${totalCharsToTranslate}`);

        // 如果没有需要翻译的行，直接完成
        if (toTranslateCount === 0) {
            console.log('[Doubao Full Translate] No lines need translation');
            const finalContent = translatedLines.join('\n');
            renderZhDocument(finalContent);
            document.getElementById('zh-content-length').textContent = finalContent.length.toString();
            showSuccess('翻译完成！（无需翻译的内容）');
            // 隐藏进度条
            setTimeout(() => {
                document.getElementById('translation-progress').style.display = 'none';
            }, 1500);
            return;
        }

        // 将需要翻译的行分成多个块（按字符数限制）
        const chunks = [];
        let currentChunk = {};
        let currentChunkSize = 0;

        const lineNums = Object.keys(linesToTranslate).map(n => parseInt(n)).sort((a, b) => a - b);

        for (const lineNum of lineNums) {
            const line = linesToTranslate[String(lineNum)];
            const lineSize = line.length + 10;  // 预留行号JSON开销

            // 如果单行超过限制，允许单独作为一个请求
            if (lineSize > MAX_CHUNK_SIZE) {
                // 先保存当前块（如果有内容）
                if (Object.keys(currentChunk).length > 0) {
                    chunks.push({ ...currentChunk });
                    currentChunk = {};
                    currentChunkSize = 0;
                }
                // 单行单独作为一个块（允许超出限制）
                chunks.push({ [String(lineNum)]: line });
                console.log(`[Doubao Full Translate] Line ${lineNum} exceeds limit (${line.length} chars), creating single-line chunk`);
                continue;
            }

            if (currentChunkSize + lineSize > MAX_CHUNK_SIZE && Object.keys(currentChunk).length > 0) {
                // 当前块已满，保存并开始新块
                chunks.push({ ...currentChunk });
                currentChunk = {};
                currentChunkSize = 0;
            }

            currentChunk[String(lineNum)] = line;
            currentChunkSize += lineSize;
        }

        // 添加最后一个块
        if (Object.keys(currentChunk).length > 0) {
            chunks.push(currentChunk);
        }

        console.log(`[Doubao Full Translate] Split into ${chunks.length} chunks`);

        // 统计变量
        let completedCount = 0;
        let totalConsumedPoints = 0;
        let lastRemainingTokens = null;

        // 翻译单个块的函数
        async function translateChunk(chunk, chunkIndex) {
            const chunkLineNums = Object.keys(chunk).map(n => parseInt(n)).sort((a, b) => a - b);
            const startLine = chunkLineNums[0];
            const endLine = chunkLineNums[chunkLineNums.length - 1];

            try {
                console.log(`[Doubao Full Translate] Translating chunk ${chunkIndex + 1}/${chunks.length} (lines ${startLine}-${endLine}, ${chunkLineNums.length} lines)...`);

                // 直接发送行号字典到后端
                const requestBody = { lines: chunk };
                if (model) {
                    requestBody.model = model;
                }
                if (reasoningEffort) {
                    requestBody.reasoning_effort = reasoningEffort;
                }
                const response = await doubaoTranslator.fetchWithTimeout(`${BACKEND_API_URL}/api/translate/en-to-zh`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    credentials: 'include',
                    body: JSON.stringify(requestBody)
                });

                if (!response.ok) {
                    const errorData = await response.json().catch(() => ({}));
                    throw new Error(errorData.detail || `HTTP ${response.status}: ${response.statusText}`);
                }

                const result = await response.json();

                // 将翻译结果更新到内存数组
                if (result.translated_lines) {
                    for (const [lineNum, translatedText] of Object.entries(result.translated_lines)) {
                        const idx = parseInt(lineNum) - 1;  // 转换为数组索引
                        if (idx >= 0 && idx < translatedLines.length) {
                            translatedLines[idx] = translatedText;
                        }
                    }

                    // === 实时保存翻译结果到本地存储 ===
                    await localDocStorage.updateLines(projectId, currentFileName, result.translated_lines);
                }

                if (result.remaining_tokens !== undefined) {
                    lastRemainingTokens = result.remaining_tokens;
                }

                totalConsumedPoints += result.consumed_points || 0;

                console.log(`[Doubao Full Translate] Chunk ${chunkIndex + 1} completed, consumed: ${result.consumed_points || 0}`);

            } catch (error) {
                console.error(`[Doubao Full Translate] Error translating chunk ${chunkIndex + 1} (lines ${startLine}-${endLine}):`, error);

                // 如果是点数不足或未登录，标记为致命错误
                if (error.message.includes('点数不足') || error.message.includes('未登录')) {
                    throw error;  // 致命错误，中断翻译
                }

                // 其他错误，保留原文（translatedLines已初始化为原文，无需处理）
                console.warn(`[Doubao Full Translate] Chunk ${chunkIndex + 1} failed, keeping original text`);
            }

            completedCount++;
            const progress = Math.round((completedCount / chunks.length) * 100);
            document.getElementById('progress-text').textContent = `翻译进度: ${progress}% (${completedCount}/${chunks.length})`;
            document.getElementById('progress-bar').style.width = `${progress}%`;

            // 更新预览
            const currentContent = translatedLines.join('\n');
            renderZhDocument(currentContent);
            document.getElementById('zh-content-length').textContent = currentContent.length.toString();
        }

        // 并行执行翻译
        console.log(`[Doubao Full Translate] Starting parallel translation with ${PARALLEL_REQUESTS} concurrent requests...`);

        for (let i = 0; i < chunks.length; i += PARALLEL_REQUESTS) {
            const batch = chunks.slice(i, i + PARALLEL_REQUESTS);
            const batchStartTime = Date.now();
            const batchNum = Math.floor(i / PARALLEL_REQUESTS) + 1;
            const totalBatches = Math.ceil(chunks.length / PARALLEL_REQUESTS);

            console.log(`[Doubao Full Translate] Processing batch ${batchNum}/${totalBatches}, chunks ${i + 1}-${Math.min(i + PARALLEL_REQUESTS, chunks.length)}`);

            try {
                await Promise.all(batch.map((chunk, idx) => translateChunk(chunk, i + idx)));
            } catch (error) {
                // 致命错误，中断翻译但保存已完成的部分
                if (error.message.includes('点数不足') || error.message.includes('未登录')) {
                    // 保存当前进度
                    const partialContent = translatedLines.join('\n');
                    await localDocStorage.save(projectId, currentFileName, partialContent);
                    console.log('[Doubao Full Translate] Partial translation saved due to error');
                    throw error;
                }
            }

            console.log(`[Doubao Full Translate] Batch ${batchNum} completed in ${Date.now() - batchStartTime}ms`);

            // 每批次完成后保存一次（防止中断丢失进度）
            const progressContent = translatedLines.join('\n');
            await localDocStorage.save(projectId, currentFileName, progressContent);
        }

        // 更新用户点数显示
        if (lastRemainingTokens !== null && currentUser) {
            currentUser.remaining_tokens = lastRemainingTokens;
            const tokenEl = document.getElementById('user-tokens');
            if (tokenEl) {
                tokenEl.textContent = Math.floor(lastRemainingTokens);
            }
        }

        // 生成最终翻译内容
        const translatedContent = translatedLines.join('\n');

        console.log(`[Doubao Full Translate] Translation completed, total consumed points: ${totalConsumedPoints}`);
        console.log(`[Doubao Full Translate] Original lines: ${totalLines}, Translated content lines: ${translatedLines.length}`);

        // === 最终保存到本地存储 ===
        await localDocStorage.save(projectId, currentFileName, translatedContent);
        console.log('[Doubao Full Translate] Final document saved to local storage');

        // 最终渲染
        renderZhDocument(translatedContent);
        document.getElementById('zh-content-length').textContent = translatedContent.length.toString();

        showSuccess(`翻译完成！消耗点数: ${totalConsumedPoints.toFixed(4)}，已保存到本地存储`);

        // 隐藏进度条
        setTimeout(() => {
            document.getElementById('translation-progress').style.display = 'none';
        }, 1500);

    } finally {
        document.getElementById('full-translate-btn').disabled = false;
    }
}

// 从本地存储加载文档
async function loadDocumentFromLocal(projectId, filename) {
    console.log(`[LocalDoc] Loading document: ${filename}`);

    const doc = await localDocStorage.load(projectId, filename);
    if (doc) {
        renderZhDocument(doc.content);
        document.getElementById('zh-content-length').textContent = doc.content.length.toString();

        const savedTime = new Date(doc.savedAt).toLocaleString();
        showSuccess(`已加载本地文档 (保存于: ${savedTime})`);
        return true;
    }
    return false;
}

// 检查并提示加载本地文档
async function checkAndLoadLocalDocument(projectId, filename) {
    const hasLocal = await localDocStorage.has(projectId, filename);
    if (hasLocal) {
        const doc = await localDocStorage.load(projectId, filename);
        if (doc) {
            const savedTime = new Date(doc.savedAt).toLocaleString();
            const confirmLoad = confirm(`发现本地已保存的文档\n保存时间: ${savedTime}\n行数: ${doc.lineCount}\n\n是否加载？`);
            if (confirmLoad) {
                await loadDocumentFromLocal(projectId, filename);
                return true;
            }
        }
    }
    return false;
}

// Translate full document using backend API
async function translateFullDocumentWithBackend(projectId, model) {
    console.log('[Backend Full Translate] Starting with model:', model);

    // Clear the Chinese document file on server
    await fetch('http://localhost:3897/clear-zh-document', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            project_id: projectId,
            filename: currentFileName
        })
    });

    const response = await fetch('http://localhost:3897/translate-full-document', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            project_id: projectId,
            filename: currentFileName,
            content: currentContent,
            model: model
        })
    });

    const reader = response.body.getReader();
    const decoder = new TextDecoder();

    while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value);
        const lines = chunk.split('\n').filter(line => line.trim());

        for (const line of lines) {
            if (line.startsWith('data: ')) {
                try {
                    const data = JSON.parse(line.slice(6));

                    if (data.progress !== undefined) {
                        document.getElementById('progress-text').textContent = `翻译进度: ${data.progress}%`;
                        document.getElementById('progress-bar').style.width = `${data.progress}%`;
                    }

                    // Refresh document preview when backend signals update
                    if (data.shouldRefresh) {
                        await fetchZhDocument();
                    }

                    if (data.done) {
                        showSuccess('翻译完成！');
                        document.getElementById('full-translate-btn').disabled = false;
                        // Final refresh
                        await fetchZhDocument();
                    }
                } catch (e) {
                    console.error('Parse error:', e);
                }
            }
        }
    }
}

// 反向翻译处理函数 (Chinese -> English)
async function handleReverseTranslate() {
    console.log('[Sidepanel] Reverse translate button clicked');

    if (!currentProjectId || !currentFileName) {
        showError('缺少项目信息');
        return;
    }

    // Get Chinese document content
    const zhContent = getZhContent();

    if (!zhContent || !zhContent.trim()) {
        showError('中文文档为空，无法翻译');
        return;
    }

    // Disable button and show progress
    document.getElementById('reverse-translate-btn').disabled = true;
    document.getElementById('translation-progress').style.display = 'block';
    document.getElementById('progress-text').textContent = '正在翻译中文文档为英文...';
    document.getElementById('progress-bar').style.width = '50%';

    const model = await getSelectedModel();
    const reasoningEffort = await getSelectedReasoningEffort();
    console.log('[Sidepanel] Reverse translate using model:', model, ', reasoningEffort:', reasoningEffort);

    try {
        let translatedEnglish = '';

        if (model === 'microsoft-translator') {
            // Use Microsoft Translator
            console.log('[Reverse Translate] Using Microsoft Translator...');
            translatedEnglish = await microsoftTranslator.translate(zhContent, 'zh-Hans', 'en');
        } else if (model === 'doubao-translation' || model === 'doubao-flash' || model === 'doubao-lite' ||
                   model === 'gemini-2.5-flash' || model === 'gemini-2.5-flash-lite' || model === 'gemini-3-pro') {
            // Use 豆包翻译 API 或 Gemini API (高级模型、极速模型、轻量模型、Gemini系列)
            console.log('[Reverse Translate] Using Translator, model:', model, ', reasoningEffort:', reasoningEffort);
            const result = await doubaoTranslator.translateZhToEn(zhContent, 0, 0, model, reasoningEffort);
            translatedEnglish = result.translated_text;

            // Update user token display if available
            if (result.remaining_tokens !== undefined && currentUser) {
                currentUser.remaining_tokens = result.remaining_tokens;
                const tokenEl = document.getElementById('user-tokens');
                if (tokenEl) {
                    tokenEl.textContent = Math.floor(result.remaining_tokens);
                }
            }
        } else {
            throw new Error(`不支持的模型: ${model}`);
        }

        // Update progress
        document.getElementById('progress-bar').style.width = '100%';
        document.getElementById('progress-text').textContent = '翻译完成，正在更新到Overleaf...';

        // Send translated content to Overleaf editor
        const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

        chrome.tabs.sendMessage(tab.id, {
            type: 'UPDATE_CONTENT',
            content: translatedEnglish,
            originalContent: currentContent
        }, (response) => {
            if (chrome.runtime.lastError) {
                console.error('[Sidepanel] Update content error:', chrome.runtime.lastError);
                showError('更新到Overleaf失败');
                document.getElementById('reverse-translate-btn').disabled = false;
            } else if (response && response.success) {
                showSuccess('全文翻译完成并已更新到Overleaf!');
                currentContent = translatedEnglish;
                document.getElementById('content-length').textContent = `${currentContent.length.toLocaleString()} characters`;
                updateLastUpdateTime(Date.now());

                // Hide progress bar after a short delay
                setTimeout(() => {
                    document.getElementById('translation-progress').style.display = 'none';
                    document.getElementById('reverse-translate-btn').disabled = false;
                }, 2000);
            } else {
                showError('更新到Overleaf失败');
                document.getElementById('reverse-translate-btn').disabled = false;
            }
        });

    } catch (error) {
        console.error('[Sidepanel] Reverse translation error:', error);
        showAIModelError('翻译失败: ' + error.message);
        document.getElementById('reverse-translate-btn').disabled = false;
        document.getElementById('translation-progress').style.display = 'none';
    }
}

// 重新加载英文文档处理函数
async function handleReloadEnglish() {
    if (!currentContent) {
        showError('未找到英文文档内容');
        return;
    }

    console.log('[Sidepanel] Reloading English document to Chinese preview');

    try {
        // 直接将英文内容复制到中文文档预览
        renderZhDocument(currentContent);

        // 更新字符统计
        updateZhCharCount();

        // 保存到本地存储
        if (currentProjectId && currentFileName) {
            await localDocStorage.save(currentProjectId, currentFileName, currentContent);
            console.log('[Sidepanel] Saved reloaded document to local storage');
        }

        document.getElementById('zh-preview-status').textContent = '(已重新加载英文版本)';

    } catch (error) {
        console.error('[Sidepanel] Error reloading English document:', error);
        showError('重新加载失败: ' + error.message);
    }
}
