import { topicToSlug } from "./topics";

export type TopicEntry = {
  slug: string;
  canonicalApiTopic: string;
  aliases: string[];
  displayName: string;
};

function toTitleCase(s: string): string {
  return s.replace(/\b\w/g, (c) => c.toUpperCase());
}

export function buildTopicCatalog(topics: string[]): TopicEntry[] {
  const groups = new Map<string, string[]>();
  for (const raw of topics) {
    const name = (raw ?? "").toString().trim();
    if (!name) continue;
    const slug = topicToSlug(name);
    if (!slug) continue;
    const arr = groups.get(slug) ?? [];
    if (!arr.includes(name)) arr.push(name);
    groups.set(slug, arr);
  }
  return Array.from(groups.entries()).map(([slug, names]) => {
    // Prefer the variant with proper-case letters; tie-break by shortest.
    const sorted = [...names].sort((a, b) => {
      const aUp = /[A-Z]/.test(a) ? 0 : 1;
      const bUp = /[A-Z]/.test(b) ? 0 : 1;
      if (aUp !== bUp) return aUp - bUp;
      return a.length - b.length;
    });
    const canonical = sorted[0];
    const display = /[A-Z]/.test(canonical) ? canonical : toTitleCase(canonical);
    return {
      slug,
      canonicalApiTopic: canonical,
      aliases: sorted.slice(1),
      displayName: display,
    };
  });
}

export function findTopicBySlug(catalog: TopicEntry[], slug: string): TopicEntry | undefined {
  return catalog.find((e) => e.slug === slug);
}
