import { prisma } from '../../models';
import { AudioMerger } from '../tts/audio-merger';
import path from 'path';

/**
 * 获取用户播放记录
 */
export async function getPlayProgress(userId: string, chapterId?: number) {
  const userIdNum = parseInt(userId);
  const where: any = { userId: userIdNum };
  if (chapterId) {
    where.chapterId = chapterId;
  }

  const records = await prisma.playRecord.findMany({
    where,
    include: {
      chapter: {
        select: {
          id: true,
          number: true,
          title: true,
          audioUrl: true,
          audioDuration: true,
        },
      },
    },
    orderBy: { updatedAt: 'desc' },
  });

  return records;
}

/**
 * 保存播放进度
 */
export async function savePlayProgress(
  userId: string,
  chapterId: number,
  progress: number,
  duration: number
) {
  const userIdNum = parseInt(userId);
  // 使用 upsert 语义：如果不存在则创建，存在则更新
  const existing = await prisma.playRecord.findUnique({
    where: {
      userId_chapterId: {
        userId: userIdNum,
        chapterId,
      },
    },
  });

  if (existing) {
    // 更新
    return await prisma.playRecord.update({
      where: {
        userId_chapterId: {
          userId: userIdNum,
          chapterId,
        },
      },
      data: {
        progress,
        duration,
      },
    });
  } else {
    // 创建
    return await prisma.playRecord.create({
      data: {
        userId: userIdNum,
        chapterId,
        progress,
        duration,
      },
    });
  }
}

/**
 * 删除播放记录
 */
export async function deletePlayRecord(userId: string, chapterId: number) {
  const userIdNum = parseInt(userId);
  return await prisma.playRecord.delete({
    where: {
      userId_chapterId: {
        userId: userIdNum,
        chapterId,
      },
    },
  });
}

/**
 * 更新播放进度
 */
export async function updatePlayProgress(
  userId: string,
  chapterId: number,
  progress: number,
  duration?: number
) {
  const userIdNum = parseInt(userId);
  const data: any = { progress };
  if (duration !== undefined) {
    data.duration = duration;
  }

  return await prisma.playRecord.update({
    where: {
      userId_chapterId: {
        userId: userIdNum,
        chapterId,
      },
    },
    data,
  });
}

/**
 * 获取单个章节的播放进度
 */
export async function getSingleProgress(userId: string, chapterId: number) {
  const userIdNum = parseInt(userId);
  const record = await prisma.playRecord.findUnique({
    where: {
      userId_chapterId: {
        userId: userIdNum,
        chapterId,
      },
    },
  });

  return record;
}

/**
 * 合并章节的所有小节音频
 * 当播放章（level=1）时，自动合并其下所有小节（level=3）的音频
 * @param chapterId 章的ID (level=1)
 * @returns 合并后的音频URL
 */
export async function mergeChapterAudios(chapterId: number): Promise<string | null> {
  // 获取章节信息
  let chapter = await prisma.bookChapter.findUnique({
    where: { id: chapterId },
  });

  if (!chapter) {
    console.error(`❌ 章节 ${chapterId} 不存在`);
    return null;
  }

  // 如果不是1级章，向上追溯到1级章（兼容调用方传入节/section的ID）
  let effectiveChapterId = chapterId;
  if (chapter.level !== 1) {
    console.log(`[MergeAudio] 当前节点 level=${chapter.level}，向上追溯1级章...`);
    let currentLevel = chapter.level;
    let currentId = chapter.id;
    let currentParentId = chapter.parentId;

    while (currentLevel > 1 && currentParentId) {
      const parent = await prisma.bookChapter.findUnique({
        where: { id: currentParentId },
        select: { id: true, level: true, parentId: true },
      });
      if (!parent) break;
      currentLevel = parent.level;
      currentId = parent.id;
      currentParentId = parent.parentId;
    }

    if (currentLevel !== 1) {
      console.log(`[MergeAudio] ⏭️ 无法找到1级章，当前追溯结果 level=${currentLevel}`);
      return null;
    }

    console.log(`[MergeAudio] 追溯到1级章 id=${currentId}，重新查询完整信息`);
    chapter = await prisma.bookChapter.findUnique({
      where: { id: currentId },
    });
    if (!chapter) {
      console.error(`❌ 追溯到的1级章 ${currentId} 不存在`);
      return null;
    }
    effectiveChapterId = chapter.id;
  }

  // 如果已经有合并后的音频（audioUrl存在且是合并后的），直接返回
  if (chapter.audioUrl && chapter.audioUrl.includes('_merged')) {
    console.log(`✅ 章节 ${chapterId} 已有合并音频: ${chapter.audioUrl}`);
    return chapter.audioUrl;
  }

  // 1. 找到所有节（level=2，parentId=章ID）
  const sections = await prisma.bookChapter.findMany({
    where: {
      parentId: effectiveChapterId,
      level: 2,
    },
    orderBy: { number: 'asc' },
  });

  if (sections.length === 0) {
    console.log(`⏭️ 章 ${effectiveChapterId} 没有子节`);
    return null;
  }

  // 2. 收集待合并的音频URL
  // 先尝试查找 level=3 小节（3层树：章→节→小节）
  const sectionIds = sections.map(s => s.id);
  const subsections = await prisma.bookChapter.findMany({
    where: {
      parentId: { in: sectionIds },
      level: 3,
      audioUrl: { not: '' },
    },
    orderBy: { number: 'asc' },
  });

  let audioFiles: string[];
  if (subsections.length > 0) {
    // 3层树：合并所有 level=3 小节音频
    audioFiles = subsections
      .map(s => s.audioUrl)
      .filter((url): url is string => !!url);
    console.log(`🔄 合并章 ${effectiveChapterId} 下 ${audioFiles.length} 个小节(level=3)音频...`);
  } else {
    // 2层树：直接合并 level=2 的节音频
    audioFiles = sections
      .filter(s => s.audioUrl && s.audioUrl !== '')
      .map(s => s.audioUrl!);
    console.log(`🔄 合并章 ${effectiveChapterId} 下 ${audioFiles.length} 个节(level=2)音频...`);
  }

  if (audioFiles.length === 0) {
    console.log(`⏭️ 章 ${effectiveChapterId} 下没有音频可合并`);
    return null;
  }

  // 3. 生成合并后的输出路径
  const uploadsDir = path.join(process.cwd(), 'uploads');
  const outputFileName = `chapter_${effectiveChapterId}_merged_${Date.now()}.mp3`;
  const outputPath = path.join(uploadsDir, outputFileName);

  // 4. 转换路径：OSS远程URL保持原样，本地路径转为绝对路径
  const absoluteAudioFiles = audioFiles.map(f => {
    if (f.startsWith('http')) return f; // OSS URL 保持原样，AudioMerger 会检测并远程处理
    const relativePath = f.replace(/^\//, '');
    return path.join(process.cwd(), relativePath);
  });

  try {
    // 5. 合并音频，捕获返回值（OSS模式返回OSS URL，本地模式返回本地路径）
    const mergeResult = await AudioMerger.merge(absoluteAudioFiles, outputPath);

    // 6. 更新章节的 audioUrl
    // 本地合并返回绝对路径需转为相对URL，OSS合并直接返回远程URL
    let mergedAudioUrl: string;
    if (mergeResult.startsWith('http')) {
      mergedAudioUrl = mergeResult; // OSS URL
    } else {
      // 本地绝对路径 → 相对URL
      const cwd = process.cwd().replace(/\\/g, '/');
      const normalized = mergeResult.replace(/\\/g, '/');
      mergedAudioUrl = normalized.startsWith(cwd)
        ? normalized.substring(cwd.length)
        : `/uploads/${outputFileName}`;
    }

    // 获取合并后音频的时长
    const mergedDuration = await AudioMerger.getDuration(mergeResult);

    await prisma.bookChapter.update({
      where: { id: effectiveChapterId },
      data: {
        audioUrl: mergedAudioUrl,
        audioDuration: mergedDuration || 0,
      },
    });

    console.log(`✅ 章节 ${effectiveChapterId} 音频合并完成: ${mergedAudioUrl}, 时长: ${mergedDuration}s`);
    return mergedAudioUrl;
  } catch (error) {
    console.error(`❌ 章节 ${effectiveChapterId} 音频合并失败:`, error);
    return null;
  }
}

/**
 * 获取章节音频URL（如果是章则自动合并小节音频）
 * @param chapterId 章节ID
 */
export async function getChapterAudioUrl(chapterId: number): Promise<string | null> {
  return await mergeChapterAudios(chapterId);
}

/**
 * 获取用户最近播放记录
 * @param userId 用户ID
 * @param limit 返回数量限制，默认10条
 * @returns 最近播放记录列表
 */
export async function getRecentPlayRecords(userId: string, limit: number = 10) {
  const userIdNum = parseInt(userId);

  const records = await prisma.playRecord.findMany({
    where: { userId: userIdNum },
    include: {
      chapter: {
        include: {
          book: {
            select: {
              id: true,
              title: true,
              coverUrl: true,
            },
          },
        },
      },
    },
    orderBy: { updatedAt: 'desc' },
    take: limit,
  });

  return records.map((record) => ({
    id: record.chapterId.toString(),
    title: record.chapter?.book?.title || record.chapter?.title || '',
    coverUrl: record.chapter?.book?.coverUrl || '',
    progress: Math.round((record.progress / (record.duration || 1)) * 100),
    updatedAt: record.updatedAt.toISOString(),
  }));
}
