import type { Character } from '@/lib/schemas';

/** Convert a Pathbuilder 2e export (build JSON) into our PF2e character fields. */

const RANK: Record<number, Character['perceptionRank']> = { 0: 'untrained', 2: 'trained', 4: 'expert', 6: 'master', 8: 'legendary' };
const PF2E_SKILLS = ['acrobatics', 'arcana', 'athletics', 'crafting', 'deception', 'diplomacy', 'intimidation', 'medicine', 'nature', 'occultism', 'performance', 'religion', 'society', 'stealth', 'survival', 'thievery'];

export interface PathbuilderBuild {
  name?: string; class?: string; level?: number; ancestry?: string; heritage?: string; background?: string;
  abilities?: Record<string, number>;
  attributes?: { ancestryhp?: number; classhp?: number; bonushp?: number; bonushpPerLevel?: number };
  proficiencies?: Record<string, number>;
}

export function isPathbuilder(raw: unknown): raw is { build: PathbuilderBuild } {
  return !!raw && typeof raw === 'object' && 'build' in raw && !!(raw as { build?: { class?: unknown } }).build?.class;
}

const rank = (v: number | undefined): Character['perceptionRank'] => RANK[v ?? 0] ?? 'untrained';

export function pathbuilderToCharacterFields(b: PathbuilderBuild): Partial<Character> {
  const a = b.abilities ?? {};
  const abilities = { str: a.str ?? 10, dex: a.dex ?? 10, con: a.con ?? 10, int: a.int ?? 10, wis: a.wis ?? 10, cha: a.cha ?? 10 };
  const level = Math.max(1, Math.min(20, b.level ?? 1));
  const conMod = Math.floor((abilities.con - 10) / 2);
  const at = b.attributes ?? {};
  const hpMax = Math.max(1, (at.ancestryhp ?? 0) + (at.bonushp ?? 0) + ((at.classhp ?? 8) + (at.bonushpPerLevel ?? 0) + conMod) * level);
  const prof = b.proficiencies ?? {};

  const saveRanks: Record<string, Character['perceptionRank']> = {};
  if (prof.fortitude) saveRanks.con = rank(prof.fortitude);
  if (prof.reflex) saveRanks.dex = rank(prof.reflex);
  if (prof.will) saveRanks.wis = rank(prof.will);

  const skillRanks: Record<string, Character['perceptionRank']> = {};
  for (const s of PF2E_SKILLS) if (prof[s]) skillRanks[s] = rank(prof[s]);

  return {
    system: 'pf2e',
    kind: 'pc',
    name: b.name?.trim() || 'Imported Character',
    className: b.class ?? '',
    ancestry: b.ancestry ?? '',
    level,
    abilities,
    hp: { current: hpMax, max: hpMax, temp: 0 },
    saveRanks: saveRanks as Character['saveRanks'],
    skillRanks: skillRanks as Character['skillRanks'],
    perceptionRank: rank(prof.perception) === 'untrained' ? 'trained' : rank(prof.perception),
    ...(b.background ? { notes: `Background: ${b.background}${b.heritage ? `\nHeritage: ${b.heritage}` : ''}` } : {}),
  };
}
