import {
  buildChapterSegments,
  type ChapterSegment,
} from "../../domain/chapters.ts";
import type { ParsedBook } from "../parsers/contracts.ts";

export interface ChapterSyncPayload {
  id: string;
  title: string;
  position: number;
  pageStart: number | null;
  pageEnd: number | null;
  segments: Array<Omit<ChapterSegment, "pageNumber"> & {
    pageNumber: number | null;
  }>;
}

export async function prepareChaptersForSync(
  bookId: string,
  parsed: ParsedBook,
): Promise<ChapterSyncPayload[]> {
  const sourceKind = parsed.format === "epub"
    ? "epub" as const
    : parsed.requiresOcr
      ? "ocr" as const
      : "pdf_text" as const;

  return Promise.all(
    parsed.chapters.map(async (chapter, position) => {
      const chapterId = `${bookId}:chapter:${position + 1}`;
      const segments = await buildChapterSegments({
        id: chapterId,
        title: chapter.title,
        position,
        pageStart: chapter.pageStart,
        pageEnd: chapter.pageEnd,
        blocks: chapter.blocks,
        sourceKind,
      });
      return {
        id: chapterId,
        title: chapter.title,
        position,
        pageStart: chapter.pageStart ?? null,
        pageEnd: chapter.pageEnd ?? null,
        segments: segments.map((segment) => ({
          ...segment,
          pageNumber: segment.pageNumber ?? null,
        })),
      };
    }),
  );
}

export function chapterBatches(
  chapters: readonly ChapterSyncPayload[],
  batchSize = 10,
): ChapterSyncPayload[][] {
  if (!Number.isInteger(batchSize) || batchSize < 1 || batchSize > 10) {
    throw new Error("章节批次大小必须在 1 到 10 之间。");
  }
  const batches: ChapterSyncPayload[][] = [];
  for (let index = 0; index < chapters.length; index += batchSize) {
    batches.push(chapters.slice(index, index + batchSize));
  }
  return batches;
}
