/**
 * Helpers that make the pf2e creator read as cleanly as the 5e one. The pf2e
 * (Foundry) data carries long, citation-prefixed descriptions and reprinted
 * entries under duplicate names; these trim and de-duplicate at the edge.
 */

/**
 * A short, clean overview from possibly-long text. Strips the
 * "<Name> Source Core Rulebook pg. N" citation prefix Foundry entries carry,
 * drops a stray trailing ellipsis from prior truncation, then keeps the first
 * sentence (or a clean word-boundary trim). A no-op on already-short text.
 */
export function briefOverview(text: string): string {
  let t = (text || '').replace(/\s+/g, ' ').trim();
  const citation = /^.{0,80}?\bSource\b.*?\bpg\.\s*\d+\s*/i.exec(t);
  if (citation) t = t.slice(citation[0].length).trim();
  t = t.replace(/…\s*$/, '').trim();
  if (t.length <= 140) return t;
  const sentence = /^(.{40,180}?[.!?])(?:\s|$)/.exec(t);
  if (sentence) return sentence[1]!;
  const cut = t.slice(0, 140);
  const sp = cut.lastIndexOf(' ');
  return `${(sp > 40 ? cut.slice(0, sp) : cut).trim()}…`;
}

/** Keep the first entry of each name (case-insensitive) — drops reprints/variants. */
export function dedupeByName<T extends { name: string }>(items: T[]): T[] {
  const seen = new Set<string>();
  return items.filter((it) => {
    const k = it.name.trim().toLowerCase();
    if (seen.has(k)) return false;
    seen.add(k);
    return true;
  });
}
