import type { Homebrew, HomebrewKind } from '@/lib/schemas';
import { abilityModifier } from '@/lib/rules';
import type { Entry } from '@/features/compendium/registry';

/** Editable scalar fields offered per homebrew kind. */
export interface FieldDef {
  key: string;
  label: string;
  type: 'number' | 'text';
}

export const HOMEBREW_FIELDS: Record<HomebrewKind, FieldDef[]> = {
  monster: [
    { key: 'AC', label: 'Armor Class', type: 'number' },
    { key: 'HP', label: 'Hit Points', type: 'number' },
    { key: 'CR', label: 'Challenge Rating', type: 'number' },
    { key: 'Dexterity', label: 'Dexterity', type: 'number' },
  ],
  spell: [
    { key: 'Level', label: 'Level', type: 'number' },
    { key: 'School', label: 'School', type: 'text' },
  ],
  item: [
    { key: 'Type', label: 'Type', type: 'text' },
    { key: 'Rarity', label: 'Rarity', type: 'text' },
  ],
  feat: [],
  condition: [],
};

export const HOMEBREW_KIND_LABEL: Record<HomebrewKind, string> = {
  monster: 'Monster',
  spell: 'Spell',
  item: 'Item',
  feat: 'Feat',
  condition: 'Condition',
};

/** Compendium category id -> homebrew kind it should merge in. */
export const CATEGORY_HOMEBREW_KIND: Record<string, HomebrewKind> = {
  '5e-monsters': 'monster', '5e-spells': 'spell', '5e-items': 'item', '5e-feats': 'feat', '5e-conditions': 'condition',
  'pf2e-creatures': 'monster', 'pf2e-spells': 'spell', 'pf2e-equipment': 'item', 'pf2e-feats': 'feat', 'pf2e-conditions': 'condition',
};

/** Convert a homebrew record into a compendium Entry (fields spread to top level). */
export function homebrewToEntry(hb: Homebrew): Entry {
  return {
    ...hb.fields,
    name: hb.name,
    slug: `hb-${hb.id}`,
    description: hb.description,
    __homebrew: true,
    __kind: hb.kind,
  };
}

export function isHomebrew(entry: Entry): boolean {
  return entry.__homebrew === true;
}

/** Combat stats for a homebrew monster entry. */
export function homebrewCombatant(entry: Entry): { name: string; ac: number; hp: number; initBonus: number; cr?: number } {
  const num = (v: unknown, d: number) => (typeof v === 'number' && Number.isFinite(v) ? v : d);
  const cr = entry.CR;
  return {
    name: entry.name,
    ac: num(entry.AC, 10),
    hp: num(entry.HP, 1),
    initBonus: abilityModifier(num(entry.Dexterity, 10)),
    ...(typeof cr === 'number' ? { cr } : {}),
  };
}
