/**
 * Structural fingerprinting for repeated-component (card) detection. PURE —
 * operates on a minimal element-shape abstraction so it is unit-testable
 * without a DOM. segment-page.ts adapts real Elements to `FingerprintNode`.
 */

export interface FingerprintNode {
  localName: string;
  className: string;
  children: FingerprintNode[];
}

export interface FingerprintOptions {
  maxDepth?: number;
  maxBreadth?: number;
}

const MEDIA_TAGS = new Set(["img", "svg", "video", "picture", "figure"]);
const CONTROL_TAGS = new Set(["input", "select", "textarea", "button"]);

/** Drops utility/state/hash classes, keeps up to 3 structurally meaningful ones. */
export function classSignature(className: string): string {
  const classes = className
    .split(/\s+/)
    .filter(Boolean)
    .filter((c) => !/\d/.test(c)) // col-4, item-2, mt-8
    .filter((c) => !/^(is|has|js|no)-/.test(c)) // state prefixes
    .filter(
      (c) =>
        !/(^|-)(active|current|selected|open|first|last|odd|even|hover|focus)$/.test(
          c,
        ),
    )
    .filter(
      (c) =>
        // CSS-module / emotion hashes: length>=5, mixes case, no dash
        !(c.length >= 5 && /[a-z]/.test(c) && /[0-9A-Z]/.test(c) && !c.includes("-")),
    );
  return classes.sort().slice(0, 3).join(".");
}

function token(node: FingerprintNode): string {
  const tag = node.localName;
  let t = tag;
  if (tag === "a") t += "@";
  if (MEDIA_TAGS.has(tag)) t += "*";
  const headingMatch = /^h([1-6])$/.exec(tag);
  if (headingMatch) t += `#${headingMatch[1]}`;
  if (CONTROL_TAGS.has(tag)) t += "!";
  return `${t}:${classSignature(node.className)}`;
}

function fp(node: FingerprintNode, depth: number, maxBreadth: number): string {
  if (depth <= 0) return token(node);
  const kids = node.children.slice(0, maxBreadth);
  return `${token(node)}(${kids.map((k) => fp(k, depth - 1, maxBreadth)).join(",")})`;
}

/** Depth-limited preorder structural signature, raw (un-hashed) string. */
export function structuralFingerprintRaw(
  node: FingerprintNode,
  opts: FingerprintOptions = {},
): string {
  return fp(node, opts.maxDepth ?? 3, opts.maxBreadth ?? 6);
}

/** Same as `LisioReaderAdapter.simpleHash` — deterministic, no new dependency. */
export function simpleHash(input: string): string {
  let hash = 0;
  for (let i = 0; i < input.length; i++) {
    const char = input.charCodeAt(i);
    hash = (hash << 5) - hash + char;
  }
  return (hash >>> 0).toString(36).padStart(7, "0");
}

export function structuralFingerprint(
  node: FingerprintNode,
  opts: FingerprintOptions = {},
): string {
  return simpleHash(structuralFingerprintRaw(node, opts));
}

export interface RepeatGroup {
  members: FingerprintNode[];
  fingerprint: string;
  similarity: number;
}

export interface RepeatOptions {
  minRepeat?: number;
  minSimilarity?: number;
  minMedianText?: number;
  /** Injected so guards (link density, container kind) can consult real features. */
  textLengthOf?: (node: FingerprintNode) => number;
  wordCountOf?: (node: FingerprintNode) => number;
  linkDensityOf?: (node: FingerprintNode) => number;
}

function median(values: number[]): number {
  if (values.length === 0) return 0;
  const sorted = [...values].sort((a, b) => a - b);
  const mid = Math.floor(sorted.length / 2);
  return sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid];
}

/**
 * Group `eligible` (element children with >=1 element child) by structural
 * fingerprint at depth 2 (coarse), then refine to depth 3 if that produces
 * still-valid subgroups (more specific structure ⇒ better cards). Falls back
 * to depth 1 (see `findRepeatGroups()`) when depth 2 finds nothing at all —
 * real card lists (e.g. a press-clippings feed aggregating externally-sourced
 * snippets) often vary enough ONE level below the card root — an empty
 * summary, a bare paragraph, a paragraph plus an injected embed widget, a
 * different wrapper tag entirely — to fragment every card's depth-2
 * fingerprint into its own singleton, even though every card shares the
 * exact same direct-child shape (image, date, title, summary, "read more").
 */
function groupAtDepth(
  withElementChildren: FingerprintNode[],
  depth: number,
  opts: Required<Pick<RepeatOptions, "minRepeat" | "minSimilarity" | "minMedianText" | "textLengthOf" | "wordCountOf" | "linkDensityOf">>,
): RepeatGroup[] {
  const { minRepeat, minSimilarity, minMedianText, textLengthOf, wordCountOf, linkDensityOf } = opts;

  const groups = new Map<string, FingerprintNode[]>();
  for (const node of withElementChildren) {
    const key = structuralFingerprint(node, { maxDepth: depth });
    const arr = groups.get(key) ?? [];
    arr.push(node);
    groups.set(key, arr);
  }

  const result: RepeatGroup[] = [];

  for (const [key, members] of groups) {
    const isAllSiblings = members.length === withElementChildren.length;
    const meetsCount = members.length >= minRepeat || (members.length === 2 && isAllSiblings);
    if (!meetsCount) continue;

    const similarity = members.length / withElementChildren.length;
    if (similarity < minSimilarity && !isAllSiblings) continue;

    // Guards
    const medianText = median(members.map(textLengthOf));
    if (medianText < minMedianText) continue;
    const medianWords = median(members.map(wordCountOf));
    const avgLinkDensity = members.reduce((s, m) => s + linkDensityOf(m), 0) / members.length;
    if (avgLinkDensity > 0.9 && medianWords < 4) continue;

    // Refine at depth 3: prefer a finer split when it still reaches minRepeat.
    const fineGroups = new Map<string, FingerprintNode[]>();
    for (const m of members) {
      const fineKey = structuralFingerprint(m, { maxDepth: 3 });
      const arr = fineGroups.get(fineKey) ?? [];
      arr.push(m);
      fineGroups.set(fineKey, arr);
    }
    const fineEntries = [...fineGroups.entries()].filter(([, v]) => v.length >= minRepeat);
    if (fineEntries.length > 0 && fineEntries.reduce((s, [, v]) => s + v.length, 0) === members.length) {
      for (const [fineKey, fineMembers] of fineEntries) {
        result.push({
          members: fineMembers,
          fingerprint: fineKey,
          similarity: fineMembers.length / withElementChildren.length,
        });
      }
    } else {
      result.push({ members, fingerprint: key, similarity });
    }
  }

  return result;
}

export function findRepeatGroups(
  eligible: FingerprintNode[],
  opts: RepeatOptions = {},
): RepeatGroup[] {
  const resolved = {
    minRepeat: opts.minRepeat ?? 3,
    minSimilarity: opts.minSimilarity ?? 0.6,
    minMedianText: opts.minMedianText ?? 15,
    textLengthOf: opts.textLengthOf ?? (() => 0),
    wordCountOf: opts.wordCountOf ?? (() => 0),
    linkDensityOf: opts.linkDensityOf ?? (() => 0),
  };

  const withElementChildren = eligible.filter((n) => n.children.length > 0);
  if (withElementChildren.length === 0) return [];

  const result = groupAtDepth(withElementChildren, 2, resolved);
  const finalResult = result.length > 0 ? result : groupAtDepth(withElementChildren, 1, resolved);

  // Largest group wins when several overlap in size class.
  return finalResult.sort((a, b) => b.members.length - a.members.length);
}
