import { BlockFeatures } from "./block-features";
import { BlockKind } from "./block-types";

/**
 * Regex vocabularies. FR + EN. Directly descended from mozilla/readability's
 * REGEXPS.positive / .negative (link density + these id/class heuristics are
 * the two highest-yield signals in that project), extended with French
 * terms Lisio's audience actually encounters.
 */
export const NAV_RE = /(^|[-_ ])(nav|navigation|menu|menubar|navbar|topbar|megamenu|primary-menu|main-menu|site-nav)([-_ ]|$)/i;
export const HEADER_RE = /(^|[-_ ])(header|masthead|banner|topbar|site-head|en-tete)([-_ ]|$)/i;
export const FOOTER_RE = /(^|[-_ ])(footer|site-footer|colophon|bottom|legal|pied-de-page|pied)([-_ ]|$)/i;
export const ASIDE_RE = /(^|[-_ ])(sidebar|side-bar|aside|widget-area|secondary|complementary|rail|connexe)([-_ ]|$)/i;
export const CRUMB_RE = /(^|[-_ ])(breadcrumb|breadcrumbs|fil-d-ariane|ariane|you-are-here)([-_ ]|$)/i;
export const CARD_RE = /(^|[-_ ])(cards?|grid|items?|tiles?|teasers?|products?|posts?|results?|actualites|news|vignette)([-_ ]|$)/i;
export const SEARCH_RE = /(^|[-_ ])(search|recherche|searchbox|search-form|quicksearch)([-_ ]|$)/i;
export const CONSENT_RE = /(cookie|consent|cmp|gdpr|rgpd|tarteaucitron|didomi|axeptio|onetrust|klaro|cookiebot|cc-banner)/i;
export const CONSENT_TEXT_RE = /(cookie|consent|rgpd|gdpr|traceur|tracker)/i;
export const CONSENT_ACTION_RE = /(accepter|refuser|accept|reject|param(é|e)trer|tout accepter|continuer sans|manage)/i;
export const LOGO_RE = /logo/i;
export const FOOTER_TEXT_RE = /(©|copyright|tous droits r(é|e)serv(é|e)s|all rights reserved|mentions l(é|e)gales|plan du site)/i;

interface Rule {
  id: string;
  w: number;
  when: (f: BlockFeatures) => boolean;
  geo?: true;
}

interface RuleTable {
  threshold: number;
  rules: Rule[];
}

const RULES: Partial<Record<BlockKind, RuleTable>> = {
  consent: {
    threshold: 60,
    rules: [
      { id: "idclass", w: 45, when: (f) => CONSENT_RE.test(f.idClass) },
      {
        id: "text-both",
        w: 55,
        when: () => false, // set via textLength/idClass proxy below; real text scan happens in features
      },
      { id: "buttons", w: 15, when: (f) => f.buttonCount >= 2 && f.textLength < 1200 },
      { id: "sticky-high-z", w: 25, geo: true, when: (f) => !!f.geometry?.isSticky && f.geometry.zIndex >= 100 },
      { id: "too-long", w: -40, when: (f) => f.textLength > 4000 },
    ],
  },
  nav: {
    threshold: 55,
    rules: [
      { id: "tag-role", w: 60, when: (f) => f.tagName === "nav" || f.role === "navigation" },
      { id: "idclass", w: 25, when: (f) => NAV_RE.test(f.idClass) },
      { id: "link-density-high", w: 20, when: (f) => f.linkDensity >= 0.7 },
      {
        id: "li-links",
        w: 15,
        when: (f) => f.listItemCount >= 3 && f.linkCount >= f.listItemCount * 0.8,
      },
      { id: "link-count", w: 10, when: (f) => f.linkCount >= 4 },
      { id: "short-links", w: 10, when: (f) => f.shortLinkRatio >= 0.8 },
      { id: "many-paragraphs", w: -20, when: (f) => f.pCount >= 2 },
      {
        id: "long-prose",
        w: -25,
        when: (f) => f.textLength > 1000 && f.linkDensity < 0.6,
      },
      {
        id: "sticky-top-full",
        w: 10,
        geo: true,
        when: (f) =>
          !!f.geometry &&
          (f.geometry.isSticky || f.geometry.top < 0.15 * f.geometry.viewportHeight) &&
          f.geometry.isFullWidth,
      },
    ],
  },
  header: {
    threshold: 55,
    rules: [
      { id: "tag-role", w: 60, when: (f) => f.tagName === "header" || f.role === "banner" },
      { id: "idclass", w: 25, when: (f) => HEADER_RE.test(f.idClass) },
      { id: "near-top", w: 15, when: (f) => f.domOrderRatio <= 0.1 },
      { id: "logo", w: 15, when: (f) => f.containsLogoImage },
      { id: "nav-child", w: 10, when: (f) => f.containsNavChild },
      {
        id: "geo-top-full",
        w: 12,
        geo: true,
        when: (f) => !!f.geometry && f.geometry.top < 0.1 * f.geometry.viewportHeight && f.geometry.isFullWidth,
      },
      { id: "geo-sticky", w: 8, geo: true, when: (f) => !!f.geometry?.isSticky },
    ],
  },
  footer: {
    threshold: 55,
    rules: [
      { id: "tag-role", w: 60, when: (f) => f.tagName === "footer" || f.role === "contentinfo" },
      { id: "idclass", w: 25, when: (f) => FOOTER_RE.test(f.idClass) },
      { id: "legal-text", w: 25, when: (f) => FOOTER_TEXT_RE.test(f.idClass) },
      { id: "near-bottom", w: 15, when: (f) => f.domOrderRatio >= 0.85 },
      { id: "link-heavy", w: 10, when: (f) => f.linkDensity >= 0.5 && f.linkCount >= 5 },
    ],
  },
  aside: {
    threshold: 50,
    rules: [
      { id: "tag-role", w: 60, when: (f) => f.tagName === "aside" || f.role === "complementary" },
      { id: "idclass", w: 25, when: (f) => ASIDE_RE.test(f.idClass) },
      { id: "low-share-linky", w: 12, when: (f) => f.docTextShare < 0.15 && f.linkDensity >= 0.5 },
      { id: "geo-narrow-column", w: 20, geo: true, when: (f) => !!f.geometry?.isNarrowColumn },
    ],
  },
  main: {
    threshold: 55,
    rules: [
      { id: "tag-role-id", w: 70, when: (f) => f.tagName === "main" || f.role === "main" || /(^| )(main|content|main-content)( |$)/.test(f.idClass) },
      {
        id: "idclass",
        w: 25,
        when: (f) => /(main|content|primary|page-content|article-body|entry-content|post-content)/.test(f.idClass),
      },
      { id: "doc-share", w: 30, when: (f) => f.docTextShare >= 0.4 },
      { id: "has-h1", w: 20, when: (f) => f.containsDocumentH1 },
      { id: "low-link-density", w: 10, when: (f) => f.linkDensity < 0.35 },
      { id: "high-link-density", w: -30, when: (f) => f.linkDensity > 0.6 },
    ],
  },
  article: {
    threshold: 50,
    rules: [
      { id: "tag-role", w: 55, when: (f) => f.tagName === "article" || f.role === "article" },
      {
        id: "prose-shape",
        w: 30,
        when: (f) => f.headingCount >= 1 && f.pCount >= 3 && f.textLength >= 400,
      },
      { id: "commas", w: 10, when: (f) => f.commaCount >= 10 },
      { id: "low-link-density", w: 10, when: (f) => f.linkDensity < 0.3 },
      { id: "text-density", w: 10, when: (f) => f.textDensity >= 20 },
    ],
  },
  cardList: {
    threshold: 60,
    rules: [
      {
        id: "repeat-strong",
        w: 45,
        when: (f) => f.siblingRepeatCount >= 3 && f.siblingSimilarity >= 0.8,
      },
      { id: "idclass", w: 15, when: (f) => CARD_RE.test(f.idClass) },
      {
        id: "list-items",
        w: 10,
        when: (f) => (f.tagName === "ul" || f.tagName === "ol") && f.listItemCount >= 3,
      },
      { id: "too-sparse", w: -20, when: (f) => f.pCount === 0 && f.textLength < 100 },
      {
        id: "geo-row-layout",
        w: 12,
        geo: true,
        when: (f) => !!f.geometry?.isRowLayout,
      },
    ],
  },
  list: {
    threshold: 50,
    rules: [
      { id: "tag-role", w: 50, when: (f) => f.tagName === "ul" || f.tagName === "ol" || f.tagName === "dl" || f.role === "list" },
      { id: "items", w: 15, when: (f) => f.listItemCount >= 2 },
    ],
  },
  table: {
    threshold: 50,
    rules: [{ id: "tag", w: 90, when: (f) => f.tagName === "table" }],
  },
  form: {
    threshold: 50,
    rules: [
      { id: "tag-role", w: 80, when: (f) => f.tagName === "form" || f.role === "form" },
      { id: "controls", w: 40, when: (f) => f.formControlCount >= 2 && f.buttonCount >= 1 },
    ],
  },
  embed: {
    threshold: 50,
    rules: [
      {
        id: "tag",
        w: 80,
        when: (f) => f.tagName === "iframe" || f.tagName === "embed" || f.tagName === "object" || f.tagName === "video",
      },
    ],
  },
  section: {
    threshold: 40,
    rules: [
      { id: "tag", w: 40, when: (f) => f.tagName === "section" },
      { id: "heading-and-text", w: 25, when: (f) => f.headingCount >= 1 && f.pCount >= 1 },
    ],
  },
};

/** Fixed priority for near-ties (within 10 points of the argmax). */
const EXCLUSION_ORDER: BlockKind[] = [
  "consent",
  "promo",
  "breadcrumb",
  "pagination",
  "search",
  "toolbar",
  "nav",
  "header",
  "footer",
  "aside",
  "main",
  "article",
  "cardList",
  "gallery",
  "list",
  "table",
  "form",
  "embed",
  "section",
  "contentGroup",
];

export interface Classification {
  kind: BlockKind;
  confidence: number;
  scores: Partial<Record<BlockKind, number>>;
  matched: Partial<Record<BlockKind, string[]>>;
}

/**
 * `calendar` is not scored here: if any leaf under the candidate has
 * name==="calendar" the caller short-circuits to `{kind:"calendar",
 * confidence:1}` before calling this function. Re-deriving that from DOM
 * features would just re-litigate explore-calendar-helper.ts.
 */
export function classifyBlock(f: BlockFeatures): Classification {
  const scores: Partial<Record<BlockKind, number>> = {};
  const matched: Partial<Record<BlockKind, string[]>> = {};

  // consent's "both text regexes match" rule needs the raw text info that
  // isn't itself a single boolean feature; approximate via idClass +
  // textLength shape plus the two regexes applied to idClass+ariaLabel,
  // which extraction folds the visible button/label text into via idClass
  // when available. Kept separate from the declarative table because it
  // needs two independent regex hits, not one `when`.
  const consentTextHit =
    CONSENT_TEXT_RE.test(f.idClass) || CONSENT_TEXT_RE.test(f.ariaLabel);
  const consentActionHit =
    CONSENT_ACTION_RE.test(f.idClass) || CONSENT_ACTION_RE.test(f.ariaLabel);

  for (const [kind, table] of Object.entries(RULES) as [BlockKind, RuleTable][]) {
    let score = 0;
    const hits: string[] = [];
    for (const rule of table.rules) {
      if (rule.id === "text-both") {
        if (consentTextHit && consentActionHit) {
          score += rule.w;
          hits.push(rule.id);
        }
        continue;
      }
      if (rule.when(f)) {
        score += rule.w;
        hits.push(rule.id);
      }
    }
    scores[kind] = score;
    if (hits.length > 0) matched[kind] = hits;
  }

  // calendar/gallery/breadcrumb/search/pagination/toolbar/promo land in
  // milestone 2; they always score 0 here (absent from RULES) and never win.
  scores.contentGroup = 0;

  // Candidates = kinds meeting their own threshold (contentGroup is always
  // eligible, threshold 0). Pick the highest score; break near-ties (within
  // 10 points of the max) by the fixed EXCLUSION_ORDER priority.
  const candidates = EXCLUSION_ORDER.filter((kind) => {
    if (kind === "contentGroup") return true;
    const score = scores[kind] ?? -Infinity;
    const threshold = RULES[kind]?.threshold ?? 0;
    return score >= threshold;
  });
  const maxScore = Math.max(...candidates.map((k) => scores[k] ?? -Infinity));
  const tied = candidates
    .filter((k) => (scores[k] ?? -Infinity) >= maxScore - 10)
    .sort((a, b) => EXCLUSION_ORDER.indexOf(a) - EXCLUSION_ORDER.indexOf(b));
  const best = tied[0] ?? "contentGroup";
  const bestScore = scores[best] ?? 0;

  const threshold = best === "contentGroup" ? 0 : (RULES[best]?.threshold ?? 0);
  const runnerUp = Math.max(
    threshold,
    ...Object.entries(scores)
      .filter(([k]) => k !== best)
      .map(([, v]) => v ?? -Infinity),
  );
  const confidence = Math.max(0, Math.min(1, (bestScore - runnerUp) / 40));

  return { kind: best, confidence, scores, matched };
}

export const RULE_TABLES = RULES;
