import { getRecipe } from '@/lib/recipes';
import { source } from '@/lib/source';
import { ArticleCards, type ArticlePage } from './article-cards';

const stopWords = new Set(`
  afin a ai ait alors au aucun aussi autre aux avec avoir bon car ce ceci cela ces cet cette
  ceux chaque chez comme comment dans de des du elle elles en encore est et ete etre eu eux
  fait faut il ils je la le les leur leurs lui ma mais me meme mes moi mon ne ni nos notre nous
  on ont ou par pas pendant peu plus pour pourquoi puis que quel quelle qui sans se ses si
  soit son sont sous sur ta te tes toi ton tous tout toute toutes tres tu un une vos votre vous y
  about after again all am an and any are as at be because been before being both but by can
  could did do does doing down during each either for from further had has have having he her
  here hers him his how if in into is it its just may me might more most must my no nor not
  of off on once only or other our out over own same she should so some such than that the
  their them then there these they this those through to too under until up very was we were
  what when where which while who whom why will with would you your
  recette recettes fiche fiches abap
`.trim().split(/\s+/));

const folderTags = new Set(['boissons', 'entrees', 'plats', 'desserts']);
type TermWeights = Map<string, number>;

function tokenize(text: string) {
  return (text.toLowerCase().normalize('NFKD').replace(/\p{M}/gu, '').replaceAll('œ', 'oe')
    .match(/\p{L}[\p{L}\p{N}]+/gu) ?? []).filter((token) => !stopWords.has(token));
}

function addField(terms: TermWeights, text: string, weight: number) {
  const counts = new Map<string, number>();
  for (const token of tokenize(text)) counts.set(token, (counts.get(token) ?? 0) + 1);
  for (const [token, count] of counts) {
    terms.set(token, (terms.get(token) ?? 0) + weight * (1 + Math.log(count)));
  }
}

type Page = ArticlePage;
const isArticle = (page: Page) => !page.data.gallery && !/(^|\/)index\.mdx?$/.test(page.path);

function documentTerms(page: Page) {
  const terms: TermWeights = new Map();
  const { title, description, tags, recipeSlug, structuredData } = page.data;
  const recipe = recipeSlug ? getRecipe(recipeSlug) : undefined;
  const body = recipe?.searchText ?? [
    ...(structuredData?.headings.map((heading) => heading.content) ?? []),
    ...(structuredData?.contents.map((block) => block.content) ?? []),
  ].join(' ');
  addField(terms, body, 1);
  addField(terms, description ?? '', 2);
  addField(terms, title, 4);
  addField(terms, (tags ?? []).filter((tag) => !folderTags.has(tag)).join(' '), 5);
  return terms;
}

function buildIndex() {
  // The folder landing pages are navigation and repeat the contents of their articles.
  const pages = source.getPages().filter(isArticle);
  const termsByPage = pages.map((page) => ({ page, terms: documentTerms(page) }));
  const frequency = new Map<string, number>();
  for (const { terms } of termsByPage) {
    for (const token of terms.keys()) frequency.set(token, (frequency.get(token) ?? 0) + 1);
  }
  const inverseFrequency = (token: string) => 1 + Math.log((pages.length + 1) / ((frequency.get(token) ?? 0) + 1));
  const vectorize = (terms: TermWeights) => {
    const weights = new Map(Array.from(terms, ([token, weight]) => [token, weight * inverseFrequency(token)]));
    const norm = Math.sqrt(Array.from(weights.values()).reduce((sum, weight) => sum + weight ** 2, 0));
    if (norm > 0) for (const [token, weight] of weights) weights.set(token, weight / norm);
    return weights;
  };
  const documents = termsByPage.map(({ page, terms }) => ({ page, vector: vectorize(terms) }));
  return { documents, vectorize, byUrl: new Map(documents.map((document) => [document.page.url, document])) };
}

let index: ReturnType<typeof buildIndex> | undefined;

export function RelatedArticles({ page, limit = 3, minScore = 0.16 }: {
  page: Page;
  limit?: number;
  minScore?: number;
}) {
  if (limit < 1 || !isArticle(page)) return null;
  index ??= buildIndex();
  const vector = index.byUrl.get(page.url)?.vector ?? index.vectorize(documentTerms(page));
  const related = index.documents
    .filter((document) => document.page.url !== page.url)
    .map((document) => {
      let score = 0;
      for (const [token, weight] of vector) score += weight * (document.vector.get(token) ?? 0);
      return { page: document.page, score };
    })
    .filter(({ score }) => score > 0 && score >= minScore)
    .sort((a, b) => b.score - a.score || a.page.url.localeCompare(b.page.url))
    .slice(0, limit);

  if (!related.length) return null;
  return (
    <section className="related-articles no-print" aria-labelledby="related-articles-title">
      <h2 id="related-articles-title">Articles similaires</h2>
      <ArticleCards pages={related.map(({ page: article }) => article)} columns={3} />
    </section>
  );
}
