<?php
// generate_indexes.php
// This script generates index files for fast Bible data access
// Run this once after updating the bible data file

$filePath = 'bibles.csv';
$indexDir = __DIR__ . '/bible_index/';

// Create index directory if it doesn't exist
if (!is_dir($indexDir)) {
    mkdir($indexDir, 0755, true);
}

echo "Generating Bible indexes...\n";

// Read the header to get translations
$handle = fopen($filePath, "r");
if (!$handle) {
    die("Error: Could not open $filePath\n");
}

$header = fgetcsv($handle, 0, "\t");
$translations = array_slice($header, 1);

// Save translations index
file_put_contents($indexDir . 'translations.json', json_encode($translations, JSON_PRETTY_PRINT));
echo "Saved translations index: " . count($translations) . " translations\n";

// Build book/chapter index with file positions
$bookIndex = [];
$currentBook = null;
$currentChapter = null;
$lineNumber = 0;
$filePosition = ftell($handle); // Position after header

while (($data = fgetcsv($handle, 0, "\t")) !== FALSE) {
    $lineNumber++;

    $verseRef = $data[0]; // e.g., "Genesis 1:1"
    if (!preg_match('/^([a-zA-Z ]+) (\d+):(\d+)$/', $verseRef, $matches)) {
        $filePosition = ftell($handle);
        continue;
    }

    $book = trim($matches[1]);
    $chapter = (int)$matches[2];
    $verse = (int)$matches[3];

    // Initialize book if new
    if (!isset($bookIndex[$book])) {
        $bookIndex[$book] = [
            'chapters' => []
        ];
        echo "Processing book: $book\n";
    }

    // Initialize chapter if new
    if (!isset($bookIndex[$book]['chapters'][$chapter])) {
        $bookIndex[$book]['chapters'][$chapter] = [
            'first_verse' => $verse,
            'last_verse' => $verse,
            'file_position' => $filePosition,
            'line_number' => $lineNumber
        ];
    } else {
        // Update last verse for this chapter
        $bookIndex[$book]['chapters'][$chapter]['last_verse'] = $verse;
    }

    $filePosition = ftell($handle);
}

fclose($handle);

// Save book index
file_put_contents($indexDir . 'book_index.json', json_encode($bookIndex, JSON_PRETTY_PRINT));
echo "Saved book index: " . count($bookIndex) . " books\n";

// Generate a separate file for each book's data for even faster access (optional but recommended)
echo "\nGenerating per-book data files...\n";
$handle = fopen($filePath, "r");
fgetcsv($handle, 0, "\t"); // Skip header

$currentBookData = [];
$currentBookName = null;

while (($data = fgetcsv($handle, 0, "\t")) !== FALSE) {
    $verseRef = $data[0];
    if (!preg_match('/^([a-zA-Z ]+) (\d+):(\d+)$/', $verseRef, $matches)) {
        continue;
    }

    $book = trim($matches[1]);
    $chapter = (int)$matches[2];
    $verse = (int)$matches[3];

    // If we're starting a new book, save the previous book's data
    if ($currentBookName !== null && $book !== $currentBookName) {
        $bookFile = $indexDir . 'book_' . sanitizeBookName($currentBookName) . '.json';
        file_put_contents($bookFile, json_encode($currentBookData, JSON_INVALID_UTF8_SUBSTITUTE));
        echo "  Saved: $currentBookName\n";
        $currentBookData = [];
    }

    $currentBookName = $book;

    // Store verse data
    if (!isset($currentBookData[$chapter])) {
        $currentBookData[$chapter] = [];
    }
    $currentBookData[$chapter][$verse] = array_slice($data, 1); // All translation texts
}

// Save the last book
if ($currentBookName !== null && !empty($currentBookData)) {
    $bookFile = $indexDir . 'book_' . sanitizeBookName($currentBookName) . '.json';
    file_put_contents($bookFile, json_encode($currentBookData, JSON_INVALID_UTF8_SUBSTITUTE));
    echo "  Saved: $currentBookName\n";
}

fclose($handle);

echo "\nIndex generation complete!\n";
echo "Index files saved in: $indexDir\n";

// Helper function to create safe filenames from book names
function sanitizeBookName($bookName) {
    return str_replace([' ', "'"], ['_', ''], strtolower($bookName));
}
?>
