import type { Monster, Spell, MagicItem } from './types';

/**
 * Lazy, cached loaders for the SRD datasets. Dynamic `import()` keeps the
 * multi-hundred-KB JSON out of the main bundle — it loads only when the user
 * opens the compendium (fixing the old app's eager MB-scale imports).
 */
let monstersCache: Monster[] | null = null;
let spellsCache: Spell[] | null = null;
let itemsCache: MagicItem[] | null = null;

export async function loadMonsters(): Promise<Monster[]> {
  if (!monstersCache) {
    const mod = await import('@/data/srd/monsters-srd.json');
    monstersCache = mod.default as unknown as Monster[];
  }
  return monstersCache;
}

export async function loadSpells(): Promise<Spell[]> {
  if (!spellsCache) {
    const mod = await import('@/data/srd/spells-srd.json');
    spellsCache = mod.default as unknown as Spell[];
  }
  return spellsCache;
}

export async function loadItems(): Promise<MagicItem[]> {
  if (!itemsCache) {
    const mod = await import('@/data/srd/magicitems-srd.json');
    itemsCache = mod.default as unknown as MagicItem[];
  }
  return itemsCache;
}

/** Build a combat-ready stat block summary from a monster. */
export function monsterToCombatant(m: Monster): {
  name: string;
  ac: number;
  hp: number;
} {
  return {
    name: m.name,
    ac: m.armor_class ?? 10,
    hp: m.hit_points ?? 1,
  };
}

export function crLabel(m: Monster): string {
  if (m.challenge_rating) return m.challenge_rating;
  if (m.cr === undefined) return '—';
  if (m.cr === 0.125) return '1/8';
  if (m.cr === 0.25) return '1/4';
  if (m.cr === 0.5) return '1/2';
  return String(m.cr);
}
