/**
 * 专辑/书籍管理 - API 路由
 */

import Router from '@koa/router';
import { Context } from 'koa';
import path from 'path';
import { bookStore } from './book-generator.store';
import { optionalAuth } from '../../middleware/auth';
import { prisma } from '../../models';

// 开发环境测试用户ID
const TEST_USER_ID = '1';

const router = new Router();

/**
 * GET /api/book-generator/albums
 * 获取专辑列表
 */
router.get('/albums', async (ctx: Context) => {
  try {
    const books = await bookStore.getAllByUser();
    // 只返回基本信息
    const albums = books.map(book => ({
      id: book.id,
      title: book.title,
      description: book.description,
      totalChapters: book.totalChapters,
      genStage: book.genStage,
      progress: book.progress,
      createdAt: book.createdAt,
    }));
    ctx.body = { code: 0, message: 'success', data: { albums } };
  } catch (error) {
    console.error('查询失败:', error);
    ctx.status = 500;
    ctx.body = { code: 1, message: error instanceof Error ? error.message : '查询失败' };
  }
});

/**
 * GET /api/book-generator/list
 * 获取书籍列表（带分页和日期过滤）
 */
router.get('/list', optionalAuth, async (ctx: Context) => {
  try {
    const { startDate, pageSize = '100' } = ctx.query as { startDate?: string; pageSize?: string };
    const userId = ctx.state.user?.userId || TEST_USER_ID;

    const pageSizeNum = parseInt(pageSize) || 100;
    const where: any = {
      OR: [
        { userId: parseInt(userId) },
        { userId: null }, // 兼容旧数据
      ],
    };

    if (startDate) {
      const start = new Date(startDate);
      where.createdAt = { gte: start };
    }

    // 获取总数
    const total = await prisma.book.count({ where });

    // 获取列表
    const books = await prisma.book.findMany({
      where,
      include: { chapters: true },
      orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
      take: pageSizeNum,
    });

    // 转换为前端需要的格式
    const list = books.map(book => ({
      id: book.id,
      title: book.title,
      description: book.description,
      totalChapters: book.totalChapters,
      genStage: book.genStage,
      progress: book.progress,
      createdAt: book.createdAt,
      updatedAt: book.updatedAt,
      chapters: book.chapters.map(ch => ({
        id: ch.id,
        title: ch.title,
        genStage: ch.genStage,
        audioUrl: ch.audioUrl,
        videoUrl: ch.videoUrl,
      })),
    }));

    ctx.body = {
      code: 0,
      message: 'success',
      data: { list, total },
    };
  } catch (error) {
    console.error('查询书籍列表失败:', error);
    ctx.status = 500;
    ctx.body = { code: 1, message: error instanceof Error ? error.message : '查询失败' };
  }
});

/**
 * POST /api/book-generator/albums
 * 创建专辑
 */
router.post('/albums', async (ctx: Context) => {
  try {
    const body = ctx.request.body as {
      title: string;
      description?: string;
    };

    if (!body.title || body.title.trim().length === 0) {
      ctx.status = 400;
      ctx.body = { code: 1, message: '请输入专辑名称' };
      return;
    }

    const book = await bookStore.create({
      title: body.title.trim(),
      description: body.description || '',
      totalChapters: 0, // 初始为 0，等待添加章节
    });

    ctx.body = {
      code: 0,
      message: '专辑创建成功',
      data: {
        id: book.id,
        title: book.title,
        description: book.description,
      },
    };
  } catch (error) {
    console.error('创建失败:', error);
    ctx.status = 500;
    ctx.body = { code: 1, message: error instanceof Error ? error.message : '创建失败' };
  }
});

/**
 * GET /api/book-generator/albums/:id/chapters
 * 获取专辑章节列表
 * 返回章（level=1）的列表，每个章包含其下所有小节的合并音频
 * 过滤规则：公开的音频 + 当前用户自己的音频
 */
router.get('/albums/:id/chapters', optionalAuth, async (ctx: Context) => {
  try {
    const bookId = ctx.params.id as string;
    const userId = ctx.state.user?.userId || TEST_USER_ID;

    // 获取专辑信息
    const book = await prisma.book.findUnique({
      where: { id: parseInt(bookId) },
    });

    if (!book) {
      ctx.status = 404;
      ctx.body = { code: 1, message: '专辑不存在' };
      return;
    }

    // 判断是否为所有者（userId为null时也视为所有者，这样无需登录也能访问自己的音频）
    const isOwner = book.userId === null || book.userId === parseInt(userId);

    // 获取所有章节
    const allChapters = await prisma.bookChapter.findMany({
      where: { bookId: parseInt(bookId) },
      orderBy: { number: 'asc' },
    });

    // 构建章(1) -> 节(2) -> 小节(3) 的树形结构
    const chapterMap = new Map<number, any>();
    const sectionMap = new Map<number, any>();

    // 先遍历，构建映射
    allChapters.forEach(c => {
      if (c.level === 1) {
        chapterMap.set(c.id, {
          id: String(c.id),
          bookId: String(c.bookId),
          number: c.number,
          title: c.title,
          wordCount: c.wordCount || 0,
          genStage: c.genStage || null,
          audioUrl: c.audioUrl || null,
          audioDuration: c.audioDuration || 0,
          videoUrl: c.videoUrl || null,
          videoDuration: c.videoDuration || 0,
          isPublic: c.isPublic,
          level: c.level,
          subsections: [], // 节和小节列表
        });
      } else if (c.level === 2) {
        sectionMap.set(c.id, {
          id: String(c.id),
          number: c.number,
          title: c.title,
          subsections: [],
        });
      }
    });

    // 收集所有小节及其音频，按章分组
    const subsectionsByChapter = new Map<number, { audioUrl: string; audioDuration: number; title: string; isPublic: boolean }[]>();

    // 先把3级小节挂到2级节下
    const sectionSubsections = new Map<number, { audioUrl: string; audioDuration: number; title: string; isPublic: boolean }[]>();
    allChapters.forEach(c => {
      if (c.level === 3 && c.parentId && c.audioUrl && c.audioUrl.trim() !== '') {
        if (!sectionSubsections.has(c.parentId)) {
          sectionSubsections.set(c.parentId, []);
        }
        sectionSubsections.get(c.parentId)!.push({
          audioUrl: c.audioUrl,
          audioDuration: c.audioDuration || 0,
          title: c.title,
          isPublic: c.isPublic || false,
        });
      }
    });

    // 把2级节挂到1级章下，并收集小节音频
    chapterMap.forEach((chapter, chapterId) => {
      subsectionsByChapter.set(chapterId, []);
    });

    allChapters.forEach(c => {
      if (c.level === 2 && c.parentId) {
        const chapter = chapterMap.get(c.parentId);
        const sectionData = sectionMap.get(c.id);
        if (chapter && sectionData) {
          // 获取这个小节的所有小节音频
          const subs = sectionSubsections.get(c.id) || [];
          chapter.subsections.push({ ...sectionData, subsections: subs });
          // 把小节音频按章汇总
          subs.forEach(s => {
            subsectionsByChapter.get(c.parentId)!.push(s);
          });
        }
      }
    });

    // 为每个章设置audioUrl
    // 优先级：1. 章自身已有的合并音频（_merged） > 2. 章自身的audioUrl > 3. 仅汇总子节时长
    // 注意：不再用 subs[0].audioUrl 覆盖章的 audioUrl，因为章的合并音频已在 mergeChapterAudios 中正确写入
    chapterMap.forEach((chapter, chapterId) => {
      const subs = subsectionsByChapter.get(chapterId) || [];
      if (subs.length > 0 && (!chapter.audioUrl || chapter.audioUrl.trim() === '')) {
        // 章自身没有音频（短文章以外的情况），仅汇总子节时长，不覆盖audioUrl
        // 前端播放章级别时会通过 player 接口自动触发合并
        chapter.audioDuration = subs.reduce((acc, s) => acc + s.audioDuration, 0);
      } else if (subs.length > 0) {
        // 章已有音频（可能是合并后的 _merged 音频），保留它，只汇总时长
        chapter.audioDuration = subs.reduce((acc, s) => acc + s.audioDuration, 0);
      }
      // 否则保持章自己的audioUrl（短文章直接生成在章上）
    });

    // 转换为数组并应用过滤规则
    let chapters = Array.from(chapterMap.values());

    // 应用公开过滤（只影响非所有者）
    if (!isOwner) {
      chapters = chapters.map(chapter => {
        // 检查是否有公开的小节音频
        const hasPublicSubsection = chapter.subsections?.some((s: any) =>
          s.subsections?.some((sub: any) => sub.isPublic === true && sub.audioUrl)
        );
        // 检查章节本身是否有公开音频
        const hasOwnPublicAudio = chapter.audioUrl &&
          chapter.audioUrl.trim() !== '' &&
          chapter.isPublic === true;
        if (!hasPublicSubsection && !hasOwnPublicAudio) {
          return {
            ...chapter,
            audioUrl: null,
          };
        }
        return chapter;
      });
    }

    ctx.body = {
      code: 0,
      message: 'success',
      data: {
        chapters,
        isOwner,
      },
    };
  } catch (error) {
    console.error('查询失败:', error);
    ctx.status = 500;
    ctx.body = { code: 1, message: error instanceof Error ? error.message : '查询失败' };
  }
});

/**
 * POST /api/book-generator/albums/:id/chapters/:chapterId/merge-audio
 * 合并章下所有小节音频为单个文件
 */
router.post('/albums/:id/chapters/:chapterId/merge-audio', optionalAuth, async (ctx: Context) => {
  try {
    const bookId = ctx.params.id as string;
    const chapterId = parseInt(ctx.params.chapterId as string);

    // 获取章信息
    const chapter = await prisma.bookChapter.findFirst({
      where: { id: chapterId, level: 1 },
    });

    if (!chapter) {
      ctx.status = 404;
      ctx.body = { code: 1, message: '章节不存在' };
      return;
    }

    // 获取这个章下所有的2级节
    const sections = await prisma.bookChapter.findMany({
      where: { parentId: chapterId, level: 2 },
      orderBy: { number: 'asc' },
    });

    // 获取每个节下所有有音频的小节
    const allAudioUrls: string[] = [];
    for (const section of sections) {
      const subsections = await prisma.bookChapter.findMany({
        where: { parentId: section.id, level: 3, audioUrl: { not: '' } },
        orderBy: { number: 'asc' },
      });
      subsections.forEach(sub => {
        if (sub.audioUrl) {
          allAudioUrls.push(sub.audioUrl);
        }
      });
    }

    if (allAudioUrls.length === 0) {
      ctx.status = 400;
      ctx.body = { code: 1, message: '没有可合并的音频' };
      return;
    }

    // 生成合并后的文件路径
    const outputDir = path.join(process.cwd(), 'uploads', 'merged', bookId);
    const outputPath = path.join(outputDir, `chapter_${chapterId}_merged.mp3`);

    // 确保目录存在
    const fs = require('fs');
    if (!fs.existsSync(outputDir)) {
      fs.mkdirSync(outputDir, { recursive: true });
    }

    // 合并音频
    const { AudioMerger } = await import('../tts/audio-merger.js');
    const mergedPath = await AudioMerger.merge(allAudioUrls, outputPath);

    // 获取合并后的时长
    const duration = await AudioMerger.getDuration(mergedPath);

    // 更新章的合并音频字段
    await prisma.bookChapter.update({
      where: { id: chapterId },
      data: {
        audioUrl: `/uploads/merged/${bookId}/chapter_${chapterId}_merged.mp3`,
        audioDuration: Math.round(duration),
      },
    });

    ctx.body = {
      code: 0,
      message: '音频合并成功',
      data: {
        audioUrl: `/uploads/merged/${bookId}/chapter_${chapterId}_merged.mp3`,
        duration: Math.round(duration),
      },
    };
  } catch (error) {
    console.error('合并音频失败:', error);
    ctx.status = 500;
    ctx.body = { code: 1, message: error instanceof Error ? error.message : '合并音频失败' };
  }
});

/**
 * GET /api/book-generator/albums/chapters/:id
 * 获取单个章节详情
 */
router.get('/albums/chapters/:id', optionalAuth, async (ctx: Context) => {
  try {
    const chapterId = parseInt(ctx.params.id as string);

    // 获取章节详情
    const chapter = await prisma.bookChapter.findUnique({
      where: { id: chapterId },
    });

    if (!chapter) {
      ctx.status = 404;
      ctx.body = { code: 1, message: '章节不存在' };
      return;
    }

    ctx.body = {
      code: 0,
      message: 'success',
      data: {
        id: String(chapter.id),
        bookId: String(chapter.bookId),
        parentId: chapter.parentId ? String(chapter.parentId) : null,
        number: chapter.number,
        title: chapter.title,
        content: chapter.content || '',
        genStage: chapter.genStage || null,
        level: chapter.level,
        audioUrl: chapter.audioUrl || null,
        audioDuration: chapter.audioDuration || 0,
        videoUrl: chapter.videoUrl || null,
        videoDuration: chapter.videoDuration || 0,
        wordCount: chapter.wordCount || 0,
        isPublic: chapter.isPublic || false,
      },
    };
  } catch (error) {
    console.error('查询章节详情失败:', error);
    ctx.status = 500;
    ctx.body = { code: 1, message: error instanceof Error ? error.message : '查询失败' };
  }
});

export default router;
