import type { Monster } from '@/lib/compendium/types';
import { asDamageType, type DamageDefenses, type DamageType } from '../types';

/**
 * Parse a free-text defense string like "cold, fire" or
 * "bludgeoning, piercing, and slashing from nonmagical attacks".
 *
 * We deliberately only enforce *clean* lists: a clause that carries a qualifier
 * ("from nonmagical attacks", "that is silvered", etc.) is dropped into `notes`
 * for the GM to read, never auto-applied — matching the "don't over-promise
 * automation" rule. Returns the clean damage types plus any leftover notes.
 */
function parseDamageList(raw: string | undefined): { types: DamageType[]; notes: string[] } {
  const types: DamageType[] = [];
  const notes: string[] = [];
  const text = (raw ?? '').trim();
  if (!text) return { types, notes };

  // Split on ';' first (distinct clauses), then commas/"and" within a clause.
  for (const clause of text.split(/;/)) {
    const c = clause.trim();
    if (!c) continue;
    // A qualifier ("from", "that aren't", "except") means it's conditional — note it.
    if (/\b(from|that|except|unless|nonmagical|magical|silvered|adamantine)\b/i.test(c)) {
      notes.push(c);
      continue;
    }
    for (const word of c.split(/,|\band\b/)) {
      const t = asDamageType(word);
      if (t && !types.includes(t)) types.push(t);
    }
  }
  return { types, notes };
}

function parseConditionList(raw: string | undefined): string[] {
  return (raw ?? '')
    .split(/,|\band\b|;/)
    .map((s) => s.trim().toLowerCase())
    .filter(Boolean);
}

/** Open5e monster → structured damage/condition defenses. */
export function normalizeMonsterDefenses(raw: Monster): DamageDefenses {
  const resist = parseDamageList(raw.damage_resistances);
  const immune = parseDamageList(raw.damage_immunities);
  const vulnerable = parseDamageList(raw.damage_vulnerabilities);
  return {
    resist: resist.types,
    immune: immune.types,
    vulnerable: vulnerable.types,
    conditionImmune: parseConditionList(raw.condition_immunities),
    notes: [...resist.notes, ...immune.notes, ...vulnerable.notes],
  };
}
