import fs from "node:fs";
import path from "node:path";
const headings = JSON.parse(fs.readFileSync(path.join(import.meta.dirname, "headings.json")));
console.log(`Books: ${headings.length}`);
// Build lookup: "bookIndex:chapterIndex:verseIndex" -> heading object
const headingLookup = {};
for (let bookIdx = 0; bookIdx < headings.length; bookIdx++) {
const book = headings[bookIdx];
for (const [ch, chapterHeadings] of Object.entries(book.chapters)) {
const chIdx = parseInt(ch) - 1;
for (const h of chapterHeadings) {
const vIdx = h.verse ?? 0;
const key = `${bookIdx}:${chIdx}:${vIdx}`;
const refStr = (h.references || [])
.map((r) => `RF:${r.book}:${r.chapter}:${r.verse}`)
headingLookup[key] = { heading: h.heading, reference: refStr };
// Map file names to language codes
const filesDir = path.join(import.meta.dirname, "files");
for (const [fileName, lang] of Object.entries(fileToLang)) {
const filePath = path.join(filesDir, fileName);
if (!fs.existsSync(filePath)) {
console.warn(`Skipping ${fileName}: file not found`);
const lines = fs.readFileSync(filePath, "utf8").split("\n");
const updatedLines = lines.map((line) => {
if (!line.trim()) return line;
const parts = line.split("|");
if (parts.length < 7) return line;
const bookName = parts[0];
const bookIdx = parts[1];
const verseText = parts.slice(6).join("|");
const key = `${bookIdx}:${chIdx}:${vIdx}`;
const entry = headingLookup[key];
const headingText = entry?.heading?.[lang] || "";
const reference = entry?.reference || "";
if (headingText) applied++;
return `${bookName}|${bookIdx}|${chIdx}|${vIdx}|${headingText}|${reference}|${verseText}`;
fs.writeFileSync(filePath, updatedLines.join("\n"), "utf8");
console.log(`Updated ${fileName}: ${applied} headings applied`);