"use strict";
/**
 * AI内容生成控制器
 */
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const router_1 = __importDefault(require("@koa/router"));
const ai_content_service_1 = require("./ai-content.service");
const learning_path_service_1 = require("./learning-path.service");
const router = new router_1.default();
// ============ 学习路径 API ============
// 创建学习路径任务
router.post('/learning-path/create', async (ctx) => {
    const { topic, mode } = ctx.request.body;
    if (!topic || topic.trim().length === 0) {
        ctx.status = 400;
        ctx.body = { code: 400, message: '请输入学习主题' };
        return;
    }
    // 验证模式
    const generationMode = mode === 'multi-agent' ? 'multi-agent' : 'progressive';
    // 获取用户ID（如果有）
    const token = ctx.request.headers.authorization?.replace('Bearer ', '');
    let userId = null;
    if (token) {
        try {
            const jwt = require('jsonwebtoken');
            const decoded = jwt.verify(token, 'my-jwt-secret-key-2024');
            userId = decoded.userId || decoded.id || null;
        }
        catch (e) { }
    }
    const task = await (0, learning_path_service_1.createLearningPath)(userId, topic, generationMode);
    ctx.body = { code: 0, message: 'success', data: task };
});
// 获取用户的学习任务列表（要放在 /:id 前面，否则 /list 会被匹配为 id=list）
router.get('/learning-path/list', async (ctx) => {
    const token = ctx.request.headers.authorization?.replace('Bearer ', '');
    let userId = null;
    if (token) {
        try {
            const jwt = require('jsonwebtoken');
            const decoded = jwt.verify(token, 'my-jwt-secret-key-2024');
            userId = decoded.userId || decoded.id || null;
        }
        catch (e) { }
    }
    const tasks = await (0, learning_path_service_1.getUserTasks)(userId);
    ctx.body = { code: 0, message: 'success', data: tasks };
});
// 获取学习路径详情（要放在 /list 后面）
router.get('/learning-path/:id', async (ctx) => {
    const id = parseInt(ctx.params.id);
    if (isNaN(id)) {
        ctx.status = 400;
        ctx.body = { code: 400, message: '无效的任务ID' };
        return;
    }
    const task = await (0, learning_path_service_1.getLearningPathDetail)(id);
    if (!task) {
        ctx.status = 404;
        ctx.body = { code: 404, message: '任务不存在' };
        return;
    }
    ctx.body = { code: 0, message: 'success', data: task };
});
// 获取渐进模式待确认状态
router.get('/learning-path/:id/pending', async (ctx) => {
    const id = parseInt(ctx.params.id);
    if (isNaN(id)) {
        ctx.status = 400;
        ctx.body = { code: 400, message: '无效的任务ID' };
        return;
    }
    const pending = await (0, learning_path_service_1.getPendingConfirmation)(id);
    if (!pending) {
        ctx.status = 404;
        ctx.body = { code: 404, message: '任务不存在' };
        return;
    }
    ctx.body = { code: 0, message: 'success', data: pending };
});
// 确认并继续生成（渐进模式）
router.post('/learning-path/:id/confirm', async (ctx) => {
    const id = parseInt(ctx.params.id);
    if (isNaN(id)) {
        ctx.status = 400;
        ctx.body = { code: 400, message: '无效的任务ID' };
        return;
    }
    const { step, confirmedIds, modifiedItems } = ctx.request.body;
    if (!step || !confirmedIds) {
        ctx.status = 400;
        ctx.body = { code: 400, message: '缺少必要参数' };
        return;
    }
    try {
        const result = await (0, learning_path_service_1.confirmAndContinue)(id, step, confirmedIds, modifiedItems);
        ctx.body = { code: 0, message: 'success', data: result };
    }
    catch (e) {
        ctx.status = 500;
        ctx.body = { code: 500, message: e.message };
    }
});
// 重新生成节点（渐进模式）
router.post('/learning-path/:id/regenerate', async (ctx) => {
    const id = parseInt(ctx.params.id);
    if (isNaN(id)) {
        ctx.status = 400;
        ctx.body = { code: 400, message: '无效的任务ID' };
        return;
    }
    const { type, nodeId, instruction } = ctx.request.body;
    if (!type || !nodeId) {
        ctx.status = 400;
        ctx.body = { code: 400, message: '缺少必要参数' };
        return;
    }
    try {
        const result = await (0, learning_path_service_1.regenerateNode)(id, type, nodeId, instruction);
        ctx.body = { code: 0, message: 'success', data: result };
    }
    catch (e) {
        ctx.status = 500;
        ctx.body = { code: 500, message: e.message };
    }
});
// 获取多Agent模式状态
router.get('/learning-path/:id/status', async (ctx) => {
    const id = parseInt(ctx.params.id);
    if (isNaN(id)) {
        ctx.status = 400;
        ctx.body = { code: 400, message: '无效的任务ID' };
        return;
    }
    const status = await (0, learning_path_service_1.getAgentStatus)(id);
    if (!status) {
        ctx.status = 404;
        ctx.body = { code: 404, message: '任务不存在' };
        return;
    }
    ctx.body = { code: 0, message: 'success', data: status };
});
// ============ 原有的 API ============
// 智能意图识别
router.get('/intent/recognize', async (ctx) => {
    const { input } = ctx.query;
    const result = await ai_content_service_1.aiContentService.recognizeIntent(input);
    ctx.body = { code: 0, message: 'success', data: result };
});
// 获取内容类型列表
router.get('/content-types', async (ctx) => {
    const result = ai_content_service_1.aiContentService.getContentTypes();
    ctx.body = { code: 0, message: 'success', data: result };
});
// 获取所有内容类型（扁平）
router.get('/content-types/all', async (ctx) => {
    const result = ai_content_service_1.aiContentService.getAllContentTypes();
    ctx.body = { code: 0, message: 'success', data: result };
});
// ============ 异步生成任务 API ============
// 创建异步生成任务
router.post('/generate-async', async (ctx) => {
    const { prompt, targetLength } = ctx.request.body;
    if (!prompt || prompt.trim().length === 0) {
        ctx.status = 400;
        ctx.body = { code: 400, message: '请输入内容描述' };
        return;
    }
    const taskId = `gen-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    const length = targetLength || 2000;
    // 创建任务记录
    ai_content_service_1.generateTasks.set(taskId, {
        id: taskId,
        status: 'generating',
        progress: 0,
        message: '正在创建生成任务...',
        createdAt: new Date(),
    });
    // 异步执行生成，不阻塞响应
    ai_content_service_1.aiContentService.generateContentAsync(taskId, prompt, length).catch(error => {
        console.error('❌ 异步内容生成失败:', error);
        const task = ai_content_service_1.generateTasks.get(taskId);
        if (task) {
            task.status = 'failed';
            task.error = error.message;
            task.message = '生成失败: ' + error.message;
        }
    });
    ctx.body = {
        code: 0,
        message: '任务已创建',
        data: { taskId, status: 'generating' }
    };
});
// 获取任务状态
router.get('/task/:taskId', async (ctx) => {
    const { taskId } = ctx.params;
    const task = ai_content_service_1.generateTasks.get(taskId);
    if (!task) {
        ctx.status = 404;
        ctx.body = { code: 404, message: '任务不存在' };
        return;
    }
    ctx.body = {
        code: 0,
        message: 'success',
        data: {
            taskId: task.id,
            status: task.status,
            progress: task.progress,
            message: task.message,
            result: task.result,
            error: task.error,
        }
    };
});
// 统一内容生成接口（同步版本，保留兼容）
router.post('/generate', async (ctx) => {
    const { prompt, targetLength } = ctx.request.body;
    const result = await ai_content_service_1.aiContentService.generateContent(prompt, targetLength || 2000);
    ctx.body = { code: 0, message: 'success', data: result };
});
// 获取行业列表
router.get('/industries', async (ctx) => {
    const result = ai_content_service_1.aiContentService.getIndustries();
    ctx.body = { code: 0, message: 'success', data: result };
});
// 行业适配
router.post('/adapt', async (ctx) => {
    const { content, industry } = ctx.request.body;
    const result = await ai_content_service_1.aiContentService.adaptContent(content, industry);
    ctx.body = { code: 0, message: 'success', data: result };
});
// 内容规划
router.post('/plan', async (ctx) => {
    const { type, theme, targetLength } = ctx.request.body;
    const result = await ai_content_service_1.aiContentService.planContent(type, theme, targetLength);
    ctx.body = { code: 0, message: 'success', data: result };
});
// 生成大纲
router.post('/outline/generate', async (ctx) => {
    const { type, theme, chapters } = ctx.request.body;
    const result = await ai_content_service_1.aiContentService.generateOutline(type, theme, chapters);
    ctx.body = { code: 0, message: 'success', data: result };
});
// 生成角色设定
router.post('/characters/generate', async (ctx) => {
    const { type, genre } = ctx.request.body;
    const result = await ai_content_service_1.aiContentService.generateCharacters(type, genre);
    ctx.body = { code: 0, message: 'success', data: result };
});
// 分步生成内容
router.post('/chunk/generate', async (ctx) => {
    const { outlineId, chapterIndex, chapterTitle, previousContent } = ctx.request.body;
    const result = await ai_content_service_1.aiContentService.generateChunk(outlineId, chapterIndex, chapterTitle, previousContent);
    ctx.body = { code: 0, message: 'success', data: result };
});
// 流式生成章节内容（SSE）
router.post('/chunk/stream', async (ctx) => {
    const { outlineId, chapterIndex, chapterTitle, previousContent } = ctx.request.body;
    ctx.set('Content-Type', 'text/event-stream');
    ctx.set('Cache-Control', 'no-cache');
    ctx.set('Connection', 'keep-alive');
    ctx.set('X-Accel-Buffering', 'no');
    try {
        for await (const chunk of ai_content_service_1.aiContentService.streamGenerateChunk(outlineId, chapterIndex, chapterTitle, previousContent)) {
            ctx.write(`data: ${JSON.stringify(chunk)}\n\n`);
        }
    }
    catch (error) {
        ctx.write(`data: ${JSON.stringify({ type: 'error', message: error.message })}\n\n`);
    }
    ctx.end();
});
// 流式生成（模拟SSE）
router.get('/stream/generate', async (ctx) => {
    const { outlineId } = ctx.query;
    ctx.set('Content-Type', 'text/event-stream');
    ctx.set('Cache-Control', 'no-cache');
    ctx.set('Connection', 'keep-alive');
    for await (const chunk of ai_content_service_1.aiContentService.streamGenerate(outlineId)) {
        ctx.write(`data: ${JSON.stringify(chunk)}\n\n`);
        if (chunk.type === 'done')
            break;
    }
    ctx.end();
});
// 创建生成任务
router.post('/task/create', async (ctx) => {
    const { type, title } = ctx.request.body;
    const result = ai_content_service_1.aiContentService.createTask(type, title);
    ctx.body = { code: 0, message: 'success', data: result };
});
// 获取任务列表
router.get('/tasks', async (ctx) => {
    const result = ai_content_service_1.aiContentService.getTasks();
    ctx.body = { code: 0, message: 'success', data: result };
});
// 章节连贯性检查
router.post('/coherence/check', async (ctx) => {
    const { chapter1, chapter2 } = ctx.request.body;
    const result = await ai_content_service_1.aiContentService.checkCoherence(chapter1, chapter2);
    ctx.body = { code: 0, message: 'success', data: result };
});
// 生成衔接段
router.post('/continuity/generate', async (ctx) => {
    const { previousChapter, nextTopic } = ctx.request.body;
    const result = await ai_content_service_1.aiContentService.generateContinuity(previousChapter, nextTopic);
    ctx.body = { code: 0, message: 'success', data: result };
});
// 敏感词检测
router.post('/sensitive/check', async (ctx) => {
    const { text } = ctx.request.body;
    const result = await ai_content_service_1.aiContentService.checkSensitive(text);
    ctx.body = { code: 0, message: 'success', data: result };
});
// 质量评分
router.post('/quality/score', async (ctx) => {
    const { text } = ctx.request.body;
    const result = await ai_content_service_1.aiContentService.scoreQuality(text);
    ctx.body = { code: 0, message: 'success', data: result };
});
// 内容优化
router.post('/optimize', async (ctx) => {
    const { text, target } = ctx.request.body;
    const result = await ai_content_service_1.aiContentService.optimizeContent(text, target);
    ctx.body = { code: 0, message: 'success', data: result };
});
// 获取支持的语言
router.get('/languages', async (ctx) => {
    const result = ai_content_service_1.aiContentService.getLanguages();
    ctx.body = { code: 0, message: 'success', data: result };
});
// 翻译并生成
router.post('/translate/generate', async (ctx) => {
    const { text, targetLang, voiceStyle } = ctx.request.body;
    const result = await ai_content_service_1.aiContentService.translateAndGenerate(text, targetLang, voiceStyle);
    ctx.body = { code: 0, message: 'success', data: result };
});
// 智能匹配BGM
router.post('/bgm/match', async (ctx) => {
    const { contentType, mood, genre } = ctx.request.body;
    const result = await ai_content_service_1.aiContentService.matchBGM(contentType, mood, genre);
    ctx.body = { code: 0, message: 'success', data: result };
});
// 获取音效列表
router.get('/sounds', async (ctx) => {
    const result = ai_content_service_1.aiContentService.getSounds();
    ctx.body = { code: 0, message: 'success', data: result };
});
// 情感调节
router.post('/emotion/adjust', async (ctx) => {
    const { text, targetEmotion } = ctx.request.body;
    const result = await ai_content_service_1.aiContentService.adjustEmotion(text, targetEmotion);
    ctx.body = { code: 0, message: 'success', data: result };
});
// 获取情感选项
router.get('/emotions', async (ctx) => {
    const result = ai_content_service_1.aiContentService.getEmotions();
    ctx.body = { code: 0, message: 'success', data: result };
});
// 多角色对话生成
router.post('/dialogue/generate', async (ctx) => {
    const { characters, scenario } = ctx.request.body;
    const result = await ai_content_service_1.aiContentService.generateDialogue(characters, scenario);
    ctx.body = { code: 0, message: 'success', data: result };
});
// SEO优化
router.post('/seo/optimize', async (ctx) => {
    const { title, content, platform } = ctx.request.body;
    const result = await ai_content_service_1.aiContentService.optimizeSEO(title, content, platform);
    ctx.body = { code: 0, message: 'success', data: result };
});
// 合规检查
router.post('/compliance/check', async (ctx) => {
    const { text, industry } = ctx.request.body;
    const result = await ai_content_service_1.aiContentService.checkCompliance(text, industry);
    ctx.body = { code: 0, message: 'success', data: result };
});
// 内容分析报告
router.get('/analytics/:contentId', async (ctx) => {
    const { contentId } = ctx.params;
    const result = await ai_content_service_1.aiContentService.generateAnalytics(contentId);
    ctx.body = { code: 0, message: 'success', data: result };
});
// 智能续写
router.post('/continue', async (ctx) => {
    const { text, direction } = ctx.request.body;
    const result = await ai_content_service_1.aiContentService.continueContent(text, direction);
    ctx.body = { code: 0, message: 'success', data: result };
});
exports.default = router;
