import { promises as fs } from "fs"; import path from "path"; import { demoBooks } from "@/data/demo-books"; import { Book } from "@/types/book"; export { getBookEntries, getBookContentCount, getBookStructureStats } from "@/lib/book-helpers"; const storageCatalogPath = path.join(process.cwd(), "storage", "books", "catalog.json"); function normalizeBooks(books: Book[]) { return books .map((book) => ({ ...book, sections: [...book.sections] .sort((a, b) => a.order - b.order) .map((section) => ({ ...section, entries: [...section.entries].sort((a, b) => a.order - b.order) })) })) .sort((a, b) => a.title.localeCompare(b.title, "zh-CN")); } export async function getBooks() { try { const raw = await fs.readFile(storageCatalogPath, "utf8"); const parsed = JSON.parse(raw) as Book[]; if (Array.isArray(parsed) && parsed.length > 0) { return normalizeBooks(parsed); } } catch { // Fall back to bundled demo books when no formal catalog exists yet. } return normalizeBooks(demoBooks); } export async function getBookById(bookId: string) { const books = await getBooks(); return books.find((book) => book.id === bookId); }