/**
 * AI内容生成控制器
 */

import Router from '@koa/router';
import { aiContentService } from './ai-content.service';

const router = new Router();

// 智能意图识别
router.get('/intent/recognize', async (ctx) => {
  const { input } = ctx.query;
  const result = await aiContentService.recognizeIntent(input as string);
  ctx.body = { code: 0, message: 'success', data: result };
});

// 获取内容类型列表
router.get('/content-types', async (ctx) => {
  const result = aiContentService.getContentTypes();
  ctx.body = { code: 0, message: 'success', data: result };
});

// 获取所有内容类型（扁平）
router.get('/content-types/all', async (ctx) => {
  const result = aiContentService.getAllContentTypes();
  ctx.body = { code: 0, message: 'success', data: result };
});

// 统一内容生成接口
router.post('/generate', async (ctx) => {
  const { type, industry, prompt, targetLength } = ctx.request.body as {
    type: string;
    industry: string;
    prompt: string;
    targetLength: number;
  };
  const result = await aiContentService.generateContent(type, industry, prompt, targetLength);
  ctx.body = { code: 0, message: 'success', data: result };
});

// 获取行业列表
router.get('/industries', async (ctx) => {
  const result = aiContentService.getIndustries();
  ctx.body = { code: 0, message: 'success', data: result };
});

// 行业适配
router.post('/adapt', async (ctx) => {
  const { content, industry } = ctx.request.body as { content: string; industry: string };
  const result = await aiContentService.adaptContent(content, industry);
  ctx.body = { code: 0, message: 'success', data: result };
});

// 内容规划
router.post('/plan', async (ctx) => {
  const { type, theme, targetLength } = ctx.request.body as { type: string; theme: string; targetLength: number };
  const result = await 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 as { type: string; theme: string; chapters: number };
  const result = await 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 as { type: string; genre: string };
  const result = await 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 as {
    outlineId: string;
    chapterIndex: number;
    chapterTitle?: string;
    previousContent?: string;
  };
  const result = await 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 as {
    outlineId: string;
    chapterIndex: number;
    chapterTitle?: string;
    previousContent?: string;
  };

  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 aiContentService.streamGenerateChunk(outlineId, chapterIndex, chapterTitle, previousContent)) {
      ctx.write(`data: ${JSON.stringify(chunk)}\n\n`);
    }
  } catch (error: any) {
    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 aiContentService.streamGenerate(outlineId as string)) {
    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 as { type: string; title: string };
  const result = aiContentService.createTask(type, title);
  ctx.body = { code: 0, message: 'success', data: result };
});

// 获取任务列表
router.get('/tasks', async (ctx) => {
  const result = aiContentService.getTasks();
  ctx.body = { code: 0, message: 'success', data: result };
});

// 章节连贯性检查
router.post('/coherence/check', async (ctx) => {
  const { chapter1, chapter2 } = ctx.request.body as { chapter1: string; chapter2: string };
  const result = await aiContentService.checkCoherence(chapter1, chapter2);
  ctx.body = { code: 0, message: 'success', data: result };
});

// 生成衔接段
router.post('/continuity/generate', async (ctx) => {
  const { previousChapter, nextTopic } = ctx.request.body as { previousChapter: string; nextTopic: string };
  const result = await aiContentService.generateContinuity(previousChapter, nextTopic);
  ctx.body = { code: 0, message: 'success', data: result };
});

// 敏感词检测
router.post('/sensitive/check', async (ctx) => {
  const { text } = ctx.request.body as { text: string };
  const result = await aiContentService.checkSensitive(text);
  ctx.body = { code: 0, message: 'success', data: result };
});

// 质量评分
router.post('/quality/score', async (ctx) => {
  const { text } = ctx.request.body as { text: string };
  const result = await aiContentService.scoreQuality(text);
  ctx.body = { code: 0, message: 'success', data: result };
});

// 内容优化
router.post('/optimize', async (ctx) => {
  const { text, target } = ctx.request.body as { text: string; target: string };
  const result = await aiContentService.optimizeContent(text, target);
  ctx.body = { code: 0, message: 'success', data: result };
});

// 获取支持的语言
router.get('/languages', async (ctx) => {
  const result = aiContentService.getLanguages();
  ctx.body = { code: 0, message: 'success', data: result };
});

// 翻译并生成
router.post('/translate/generate', async (ctx) => {
  const { text, targetLang, voiceStyle } = ctx.request.body as { text: string; targetLang: string; voiceStyle: string };
  const result = await 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 as { contentType: string; mood: string; genre: string };
  const result = await aiContentService.matchBGM(contentType, mood, genre);
  ctx.body = { code: 0, message: 'success', data: result };
});

// 获取音效列表
router.get('/sounds', async (ctx) => {
  const result = aiContentService.getSounds();
  ctx.body = { code: 0, message: 'success', data: result };
});

// 情感调节
router.post('/emotion/adjust', async (ctx) => {
  const { text, targetEmotion } = ctx.request.body as { text: string; targetEmotion: string };
  const result = await aiContentService.adjustEmotion(text, targetEmotion);
  ctx.body = { code: 0, message: 'success', data: result };
});

// 获取情感选项
router.get('/emotions', async (ctx) => {
  const result = aiContentService.getEmotions();
  ctx.body = { code: 0, message: 'success', data: result };
});

// 多角色对话生成
router.post('/dialogue/generate', async (ctx) => {
  const { characters, scenario } = ctx.request.body as { characters: Array<{ name: string; voice: string }>; scenario: string };
  const result = await 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 as { title: string; content: string; platform: string };
  const result = await 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 as { text: string; industry: string };
  const result = await 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 aiContentService.generateAnalytics(contentId);
  ctx.body = { code: 0, message: 'success', data: result };
});

// 智能续写
router.post('/continue', async (ctx) => {
  const { text, direction } = ctx.request.body as { text: string; direction: string };
  const result = await aiContentService.continueContent(text, direction);
  ctx.body = { code: 0, message: 'success', data: result };
});

export default router;
