#!/usr/bin/env node
/*
 * Replace the MariaDB bestiary table from the sanitized active bestiary JSON.
 * JSON remains a fallback/mirror; the app reads MariaDB first when available.
 */
const fs = require('fs');
const path = require('path');
const { pool, bestiaryHelpers, initializationPromise } = require('../database/mariadb');

const ROOT = path.join(__dirname, '..');
const SOURCE = path.join(ROOT, 'public', 'deathwatch-bestiary-extracted.json');

function loadEntries() {
  const raw = JSON.parse(fs.readFileSync(SOURCE, 'utf8'));
  const entries = Array.isArray(raw) ? raw : (raw.results || raw.entries || raw.items || []);
  if (!Array.isArray(entries)) throw new Error(`Unsupported bestiary JSON shape: ${SOURCE}`);
  return entries.filter(entry => entry && (entry.bestiaryName || entry.name));
}

async function ensureTable() {
  await pool.execute(`
    CREATE TABLE IF NOT EXISTS bestiary (
      id INT AUTO_INCREMENT PRIMARY KEY,
      name VARCHAR(255) NOT NULL,
      book VARCHAR(255),
      page VARCHAR(50),
      pdf VARCHAR(255),
      stats TEXT,
      profile TEXT,
      snippet TEXT,
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
      INDEX idx_bestiary_name (name),
      INDEX idx_bestiary_book_page (book, page)
    )
  `);
}

async function main() {
  const entries = loadEntries();
  await initializationPromise;
  await ensureTable();
  const count = await bestiaryHelpers.replaceAll(entries);
  console.log(`Imported ${count} bestiary entries into MariaDB bestiary table`);
}

main()
  .catch(error => {
    console.error(error);
    process.exitCode = 1;
  })
  .finally(async () => {
    await pool.end();
  });
