import { readFileSync } from 'fs';
import type { ChapterView } from '../types.ts';

interface ChapterRow {
  chapter: number;
  contents: string[];
}

function readChapterContents(filePath: string): string[] {
  try {
    const fragments = JSON.parse(readFileSync(filePath, 'utf-8')) as Array<{ body: string }>;
    return fragments.map(f => f.body).filter(Boolean);
  } catch {
    return [];
  }
}

export function renderJson(view: ChapterView): string {
  const rows: ChapterRow[] = view.chapters.map((chapter, i) => ({
    chapter: view.min + i,
    contents: readChapterContents(chapter.path),
  }));
  return JSON.stringify(rows);
}
