import Router from '@koa/router';
import { Context } from 'koa';
import path from 'path';
import fs from 'fs';
import * as TtsService from './tts.service';
import { BadRequestError, NotFoundError } from '../../middleware/errorHandler';
import { optionalAuth } from '../../middleware/auth';
import { usageLimitMiddleware, checkWordLimit } from '../../middleware/usageLimit';
import { checkAudioQuota } from '../subscription/subscription.service';
import { prisma } from '../../models';
import * as DocumentParser from './document-parser.service';

const router = new Router();

// 获取可用音色列表
router.get('/voices', async (ctx: Context) => {
  const voices = TtsService.getVoices();
  const baseUrl = `${ctx.protocol}://${ctx.host}`;

  // 为每个音色注入本地预览URL
  const result = voices.map(v => ({
    ...v,
    preview: fs.existsSync(path.join(process.cwd(), '..', 'voices', `${v.id}.mp3`))
      ? `${baseUrl}/tts/voices/${v.id}.mp3`
      : undefined,
  }));

  ctx.body = {
    code: 0,
    message: 'success',
    data: { voices: result },
  };
});

// 获取可用 TTS 服务商列表
router.get('/providers', async (ctx: Context) => {
  const providers = TtsService.getAvailableProviders();

  ctx.body = {
    code: 0,
    message: 'success',
    data: { providers },
  };
});

// 测试 MySQL 连接
router.get('/test-db', async (ctx: Context) => {
  try {
    const count = await prisma.book.count();
    ctx.body = {
      code: 0,
      message: 'success',
      data: { count, connectionState: 'connected' },
    };
  } catch (error: any) {
    ctx.body = {
      code: 500,
      message: 'error',
      data: { error: error.message },
    };
  }
});

// 生成音频（异步模式 - 复用有声书生成立逻辑）
router.post(
  '/generate',
  optionalAuth,
  async (ctx: Context) => {
    const userId = ctx.state.user?.userId;
    const { text, voiceId, voiceParams, bookId, chapterTitle } = ctx.request.body as {
      text: string;
      voiceId: string;
      voiceParams?: { speed?: number; pitch?: number; volume?: number };
      bookId?: string;
      chapterTitle?: string;
    };

    // 调试日志
    console.log('📥 收到 TTS 请求:', { textLength: text?.length, voiceId, voiceParams, bookId, chapterTitle });

    // 参数验证
    if (!text || text.trim().length === 0) {
      throw new BadRequestError('请输入要转换的文本');
    }

    if (text.trim().length < 10) {
      throw new BadRequestError('文本过短，至少需要10个字符');
    }

    if (!voiceId) {
      throw new BadRequestError('请选择音色');
    }

    // 如果指定了 bookId，验证书籍是否存在
    if (bookId) {
      const book = await prisma.book.findUnique({ where: { id: parseInt(bookId) } });
      if (!book) {
        throw new NotFoundError('书籍不存在');
      }
    }

    // ========== 统一音频分钟配额检查 ==========
    const wordCount = text.length;
    const effectiveUserId = userId ? parseInt(userId) : null;

    if (effectiveUserId) {
      const audioQuota = await checkAudioQuota(effectiveUserId, wordCount);
      if (!audioQuota.allowed) {
        throw new BadRequestError(audioQuota.reason as string);
      }
    }

    // 默认参数
    const params = {
      speed: voiceParams?.speed || 1.0,
      pitch: voiceParams?.pitch || 0,
      volume: voiceParams?.volume || 50,
    };

    // 复用有声书生成立逻辑：创建章节 + 入队 TtsTask，立即返回
    const result = await TtsService.requestTtsGeneration(userId, text, voiceId, params, {
      bookId,
      chapterTitle,
    });

    ctx.body = {
      code: 0,
      message: '音频生成任务已创建，正在排队处理',
      data: result, // { chapterId, bookId }
    };
  }
);

// 获取音频生成状态
router.get('/status/:audioId', async (ctx: Context) => {
  const { audioId } = ctx.params;
  const result = await TtsService.getAudioStatus(audioId);

  if (result.status === 'not_found') {
    throw new NotFoundError('音频不存在');
  }

  ctx.body = {
    code: 0,
    message: 'success',
    data: result,
  };
});

// 获取章节音频生成状态（供前端轮询）
router.get('/chapter-status/:chapterId', async (ctx: Context) => {
  const { chapterId } = ctx.params;
  const id = parseInt(chapterId);

  if (isNaN(id)) {
    throw new BadRequestError('无效的章节ID');
  }

  const chapter = await prisma.bookChapter.findUnique({
    where: { id },
    select: {
      id: true,
      genStage: true,
      audioUrl: true,
      audioDuration: true,
      title: true,
    },
  });

  if (!chapter) {
    throw new NotFoundError('章节不存在');
  }

  ctx.body = {
    code: 0,
    message: 'success',
    data: {
      chapterId: chapter.id,
      genStage: chapter.genStage,
      audioUrl: chapter.audioUrl,
      audioDuration: chapter.audioDuration,
      title: chapter.title,
      isReady: chapter.genStage === 'audio_completed' || chapter.genStage === 'video_generating' || chapter.genStage === 'video_completed',
      isFailed: chapter.genStage === 'failed',
    },
  };
});

// 预览音色 - 优先使用本地样本文件，不存在时才调用API生成
router.post('/preview', async (ctx: Context) => {
  const { voiceId } = ctx.request.body as {
    voiceId: string;
    voiceParams?: { speed?: number; pitch?: number; volume?: number };
  };

  if (!voiceId) {
    throw new BadRequestError('请选择音色');
  }

  const baseUrl = `${ctx.protocol}://${ctx.host}`;
  const localFile = `/tts/voices/${voiceId}.mp3`;
  const filePath = path.join(process.cwd(), '..', 'voices', `${voiceId}.mp3`);

  // 检查本地样本文件是否存在
  if (fs.existsSync(filePath)) {
    console.log(`🎵 [Preview] 使用本地样本: ${voiceId}`);
    ctx.body = {
      code: 0,
      message: 'success',
      data: {
        previewText: `${voiceId} 音色试听`,
        voiceId,
        audioUrl: `${baseUrl}${localFile}`,
      },
    };
    return;
  }

  // 本地不存在，降级到 API 生成
  console.log(`🔊 [Preview] 本地无样本，API生成: ${voiceId}`);
  const previewText = '你好，欢迎使用AI有声书';

  try {
    const result = await TtsService.generatePreview(voiceId, undefined, undefined);
    ctx.body = {
      code: 0,
      message: 'success',
      data: { previewText, voiceId, audioUrl: result.audioUrl },
    };
  } catch (error: any) {
    ctx.body = {
      code: 500,
      message: '预览生成失败：' + error.message,
      data: null,
    };
  }
});

// 获取音频下载信息
router.get('/download/:audioId', async (ctx: Context) => {
  const { audioId } = ctx.params;
  
  try {
    const audioRecord = await prisma.audioRecord.findUnique({
      where: { id: parseInt(audioId) },
    });

    if (!audioRecord) {
      throw new NotFoundError('音频不存在');
    }

    // 检查是否有音频URL
    if (!audioRecord.audioUrl) {
      throw new NotFoundError('音频文件不存在');
    }

    // 返回下载信息（前端直接使用 URL 下载）
    ctx.body = {
      code: 0,
      message: 'success',
      data: {
        id: audioRecord.id,
        title: audioRecord.title,
        audioUrl: audioRecord.audioUrl,
        duration: audioRecord.audioDuration,
        size: audioRecord.audioSize,
        downloadUrl: audioRecord.audioUrl, // 直接使用音频URL下载
      },
    };
  } catch (error: any) {
    if (error instanceof NotFoundError) {
      throw error;
    }
    console.error('获取下载信息失败:', error);
    ctx.status = 500;
    ctx.body = { code: 500, message: '获取下载信息失败: ' + error.message };
  }
});

// 批量下载音频（获取下载链接列表）
router.post('/download/batch', async (ctx: Context) => {
  const { audioIds } = ctx.request.body as { audioIds: string[] };

  if (!audioIds || audioIds.length === 0) {
    throw new BadRequestError('请选择要下载的音频');
  }

  if (audioIds.length > 50) {
    throw new BadRequestError('一次最多下载50个音频');
  }

  try {
    const audios = await prisma.audioRecord.findMany({
      where: {
        id: {
          in: audioIds.map(id => parseInt(id)),
        },
      },
      select: {
        id: true,
        title: true,
        audioUrl: true,
        audioDuration: true,
        audioSize: true,
      },
    });

    // 过滤出有音频URL的记录
    const validAudios = audios.filter(a => a.audioUrl);

    ctx.body = {
      code: 0,
      message: 'success',
      data: {
        total: validAudios.length,
        audios: validAudios.map(a => ({
          id: a.id,
          title: a.title,
          downloadUrl: a.audioUrl,
          duration: a.audioDuration,
          size: a.audioSize,
        })),
      },
    };
  } catch (error: any) {
    console.error('批量下载失败:', error);
    ctx.body = { code: 500, message: '批量下载失败: ' + error.message };
  }
});

// 上传文档并解析文本
router.post('/upload-document', optionalAuth, async (ctx: Context) => {
  const files = (ctx.request as any).files;
  const file = files?.file;

  if (!file) {
    throw new BadRequestError('请选择要上传的文档');
  }

  // koa-body 可能返回数组或单文件
  const uploadedFile = Array.isArray(file) ? file[0] : file;

  if (!uploadedFile) {
    throw new BadRequestError('上传文件无效');
  }

  const filePath = uploadedFile.filepath || uploadedFile.path;
  const originalName = uploadedFile.originalFilename || uploadedFile.name || 'unknown';
  const fileSize = uploadedFile.size || 0;

  console.log(`📄 [Document] 收到上传: ${originalName} (${(fileSize / 1024).toFixed(1)}KB)`);

  try {
    const result = await DocumentParser.parseDocument(filePath, originalName, fileSize);

    console.log(`✅ [Document] 解析成功: ${result.wordCount}字`);

    ctx.body = {
      code: 0,
      message: '文档解析成功',
      data: {
        text: result.text,
        wordCount: result.wordCount,
        fileName: result.fileName,
        fileSize: result.fileSize,
        format: result.format,
        truncated: result.truncated,
        originalLength: result.originalLength,
      },
    };
  } catch (error: any) {
    console.error(`❌ [Document] 解析失败:`, error.message);
    throw new BadRequestError(error.message || '文档解析失败');
  } finally {
    // 清理临时文件
    try {
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }
    } catch {
      // 忽略清理错误
    }
  }
});

export default router;