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

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

function readChapterContents(filePath: string, hasStyle: boolean): string[] | TextFragment[] {
  try {
    const raw = readFileSync(filePath, 'utf-8');
    if (hasStyle) {
      return JSON.parse(raw) as TextFragment[];
    }
    return raw.split(/[\n\r]+/).map(l => l.trim()).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, chapter.hasStyle),
  }));
  return JSON.stringify(rows);
}
