/**
 * 专辑/书籍管理 - 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();

/**
 * 获取专辑列表 handler
 */
async function getAlbums(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/books
router.get('/books', getAlbums);

/**
 * 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 : '查询失败' };
  }
});

/**
 * 创建专辑 handler
 */
async function createAlbum(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,
    });

    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 : '创建失败' };
  }
}

// POST /api/book-generator/books
router.post('/books', createAlbum);

/**
 * GET /api/book-generator/books/:id
 * 获取单个书籍详情（用于编辑页面回填）
 */
router.get('/books/:id', optionalAuth, async (ctx: Context) => {
  try {
    const bookId = parseInt(ctx.params.id as string);
    const book = await prisma.book.findUnique({
      where: { id: bookId },
      include: { chapters: { orderBy: { number: 'asc' } } },
    });

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

    ctx.body = {
      code: 0,
      message: 'success',
      data: {
        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,
        })),
      },
    };
  } catch (error) {
    console.error('查询书籍失败:', error);
    ctx.status = 500;
    ctx.body = { code: 1, message: error instanceof Error ? error.message : '查询失败' };
  }
});

/**
 * POST /api/book-generator/books/:id
 * 更新书籍（书名、描述等）
 */
router.post('/books/:id', optionalAuth, async (ctx: Context) => {
  try {
    const bookId = parseInt(ctx.params.id as string);
    const body = ctx.request.body as {
      title?: string;
      description?: string;
      bookScale?: string;
      style?: string;
    };

    const existing = await prisma.book.findUnique({ where: { id: bookId } });
    if (!existing) {
      ctx.status = 404;
      ctx.body = { code: 1, message: '书籍不存在' };
      return;
    }

    const data: any = {};
    if (body.title !== undefined) data.title = body.title;
    if (body.description !== undefined) data.description = body.description;
    if (body.bookScale !== undefined) data.bookScale = body.bookScale;
    if (body.style !== undefined) data.style = body.style;

    const updated = await prisma.book.update({
      where: { id: bookId },
      data,
    });

    ctx.body = {
      code: 0,
      message: '更新成功',
      data: { id: updated.id, title: updated.title },
    };
  } catch (error) {
    console.error('更新书籍失败:', error);
    ctx.status = 500;
    ctx.body = { code: 1, message: error instanceof Error ? error.message : '更新失败' };
  }
});

/**
 * 获取专辑章节列表 handler
 * 返回章（level=1）的列表，每个章包含其下所有小节的合并音频
 * 过滤规则：公开的音频 + 当前用户自己的音频
 */
async function getChapters(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;
    }

    const isOwner = book.userId === null || book.userId === parseInt(userId);

    const allChapters = await prisma.bookChapter.findMany({
      where: { bookId: parseInt(bookId) },
      orderBy: { number: 'asc' },
    });

    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 }[]>();
    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,
        });
      }
    });

    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);
          });
        }
      }
    });

    chapterMap.forEach((chapter, chapterId) => {
      const subs = subsectionsByChapter.get(chapterId) || [];
      if (subs.length > 0 && (!chapter.audioUrl || chapter.audioUrl.trim() === '')) {
        chapter.audioDuration = subs.reduce((acc, s) => acc + s.audioDuration, 0);
      } else if (subs.length > 0) {
        chapter.audioDuration = subs.reduce((acc, s) => acc + s.audioDuration, 0);
      }
    });

    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 : '查询失败' };
  }
}

// GET /api/book-generator/books/:id/chapters
router.get('/books/:id/chapters', optionalAuth, getChapters);

/**
 * POST /api/book-generator/books/:id/chapters/:chapterId/merge-audio
 * 合并章下所有小节音频为单个文件
 */
router.post('/books/: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 : '合并音频失败' };
  }
});

/**
 * 获取单个章节详情 handler
 */
async function getChapterDetail(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 : '查询失败' };
  }
}

// GET /api/book-generator/books/chapters/:id
router.get('/books/chapters/:id', optionalAuth, getChapterDetail);

export default router;
