import type { Chapter, ChapterViewModel, ImageAsset } from './types'; function countByStatus(images: ImageAsset[], status: string): number { return images.filter((img) => img.status === status).length; } export function toChapterViewModel(chapter: Chapter): ChapterViewModel { const images = chapter.images ?? []; const cover = chapter.cover_asset ?? null; const imagesForStatus = cover ? [cover, ...images] : images; const completedCount = countByStatus(imagesForStatus, 'completed'); const hasContent = !!(chapter.canonical_markdown ?? '').trim() || !!(chapter.summary ?? '').trim(); const wordCountFromMarkdown = (chapter.canonical_markdown ?? '').length; const wordCount = typeof chapter.word_count === 'number' && chapter.word_count >= 0 ? chapter.word_count : wordCountFromMarkdown; return { id: chapter.id, title: chapter.title, category: chapter.category, orderIndex: chapter.order_index, isEmpty: !hasContent, isNew: chapter.is_new, hasImages: imagesForStatus.length > 0, allImagesReady: imagesForStatus.length > 0 && completedCount === imagesForStatus.length, pendingImageCount: countByStatus(imagesForStatus, 'pending') + countByStatus(imagesForStatus, 'processing'), failedImageCount: countByStatus(imagesForStatus, 'failed'), coverImageUrl: cover?.url ?? null, updatedAt: chapter.updated_at, wordCount, }; } export function toChapterViewModels(chapters: Chapter[]): ChapterViewModel[] { return chapters.map(toChapterViewModel); }