// THE GENERIC EXTRACTOR (release 37 S1): any captured page as ONE record — its // readable text, title, author, date, links and images — for every capture no // site extractor claims (articles, personal sites, a group's // old site). Pure: no network, no disk, no clock (a PageExtractor). // // What it does, in order: // 1. Wayback's own chrome goes: the injected toolbar (`` … `END`, and any `#wm-ipp*` element left by a // truncated one), its scripts (`/_static/`, `wombat`, `__wm.` calls) and // stylesheets. An `id_` body usually has none; a framed one does. // 2. The page's furniture goes: nav, header and footer (a header INSIDE an // article stays — it holds the title), aside, script, style, noscript, // form, iframe, svg, buttons, the hidden. // 3. The main content: `
` / `[role=main]`, else the page's top-level // `
`s, else the densest block (each paragraph scores its parent // fully and its grandparent by half, the total cut by the block's link // density; the first highest wins). // 4. Its text, block by block: headings, paragraphs, list items ("- "), // blockquotes ("> "), `
` as written, link text, image alts.
//   5. Title from og:title, else ``, else the first h1; author and date
//      from JSON-LD, `<meta>` (author, article:published_time, og:*,
//      twitter:*, dc.*) and `<time datetime>` — a date after the capture is
//      not believed.
//   6. links[] absolute (resolved against the ORIGINAL url, Wayback-rewritten
//      hrefs un-rewritten to the original); media[] the images, each by its
//      own Wayback URL (`/web/<ts>im_/<src>`).
// A text/plain or application/json body is its text as it is.

import { parseHtml, type HtmlElement, type HtmlNode } from "../../../social/htmlReader";
import { parseWaybackUrl } from "../../wayback";
import type { PostMedia } from "../../posts";
import type { PageExtractInput, PageExtractor, PageRecordDraft } from "../types";
import { bareMimetype, captureTsIso } from "../urls";

export const GENERIC_EXTRACTOR_NAME = "generic";
export const GENERIC_EXTRACTOR_VERSION = 1;

export const NO_CONTENT_TEXT = "No readable text in this capture.";

const MAX_LINKS = 500;
const MAX_MEDIA = 200;

// ─── Wayback's chrome ───

const TOOLBAR_RE = /<!--\s*BEGIN WAYBACK TOOLBAR INSERT\s*-->[\s\S]*?<!--\s*END WAYBACK TOOLBAR INSERT\s*-->/gi;
const WAYBACK_SCRIPT_RE = /<script\b[^>]*\bsrc\s*=\s*["']?[^"'>\s]*(?:\/_static\/|wombat|archive\.org\/static\/)[^>]*>[\s\S]*?<\/script\s*>/gi;
const WM_INLINE_SCRIPT_RE = /<script\b[^>]*>(?:(?!<\/script)[\s\S])*?(?:__wm\.|wombat|_wb_wombat|WB_wombat)(?:(?!<\/script)[\s\S])*?<\/script\s*>/gi;
const WAYBACK_LINK_RE = /<link\b[^>]*\bhref\s*=\s*["']?[^"'>\s]*\/_static\/[^>]*>/gi;

// The page with the Wayback Machine's own insertions taken out.
export function stripWaybackChrome(html: string): string {
  return html
    .replace(TOOLBAR_RE, "")
    .replace(WAYBACK_SCRIPT_RE, "")
    .replace(WM_INLINE_SCRIPT_RE, "")
    .replace(WAYBACK_LINK_RE, "");
}

// A Wayback-rewritten href (`/web/<ts>[mod]/<original>`, on or off the
// archive's host) as the original URL it points at; any other href as given.
export function unrewriteWaybackUrl(href: string): string {
  const h = href.trim();
  let abs: string | null = null;
  if (/^\/web\/\d{1,14}/i.test(h)) abs = `https://web.archive.org${h}`;
  else if (/^\/\/(?:web|wayback)\.archive\.org\//i.test(h)) abs = `https:${h}`;
  else if (/^https?:\/\/(?:web|wayback)\.archive\.org\/web\/\d{1,14}/i.test(h)) abs = h;
  if (!abs) return h;
  return parseWaybackUrl(abs)?.originalUrl ?? h;
}

// An href as an absolute http(s) URL of the original web, or null.
export function absoluteOriginalUrl(href: string | undefined, originalUrl: string): string | null {
  if (!href) return null;
  const h = unrewriteWaybackUrl(href);
  if (!h || h.startsWith("#") || /^(?:javascript|mailto|tel|data|about):/i.test(h)) return null;
  try {
    const u = new URL(h, originalUrl);
    if (u.protocol !== "http:" && u.protocol !== "https:") return null;
    u.hash = "";
    return u.toString();
  } catch {
    return null;
  }
}

// An image of the capture, as the Wayback Machine serves it.
export function waybackImageUrl(captureTs: string, src: string): string {
  return `https://web.archive.org/web/${captureTs}im_/${src}`;
}

// ─── The tree ───

const isEl = (n: HtmlNode): n is HtmlElement => typeof n !== "string";

function walk(el: HtmlElement, visit: (e: HtmlElement, parent: HtmlElement) => boolean | void): void {
  for (const c of el.children) {
    if (!isEl(c)) continue;
    if (visit(c, el) === false) continue;
    walk(c, visit);
  }
}

function findAll(el: HtmlElement, pred: (e: HtmlElement) => boolean, nested = true): HtmlElement[] {
  const out: HtmlElement[] = [];
  walk(el, (e) => {
    if (pred(e)) {
      out.push(e);
      if (!nested) return false;
    }
  });
  return out;
}

function first(el: HtmlElement, pred: (e: HtmlElement) => boolean): HtmlElement | null {
  let hit: HtmlElement | null = null;
  walk(el, (e) => {
    if (hit) return false;
    if (pred(e)) {
      hit = e;
      return false;
    }
  });
  return hit;
}

function rawText(el: HtmlElement): string {
  let s = "";
  for (const c of el.children) s += isEl(c) ? rawText(c) : c;
  return s;
}

const collapse = (s: string) => s.replace(/[\s ]+/g, " ").trim();

const DROP_TAGS = new Set([
  "head", "script", "style", "noscript", "template", "nav", "aside", "form", "iframe", "frame", "frameset",
  "svg", "button", "select", "option", "input", "textarea", "canvas", "object", "embed", "menu", "dialog",
  "link", "meta",
]);
const DROP_ROLES = new Set(["navigation", "banner", "contentinfo", "complementary", "search", "menu", "menubar", "dialog"]);

function isHidden(e: HtmlElement): boolean {
  if ("hidden" in e.attrs) return true;
  if (e.attrs["aria-hidden"] === "true") return true;
  return /display\s*:\s*none|visibility\s*:\s*hidden/i.test(e.attrs.style ?? "");
}

function isWaybackChrome(e: HtmlElement): boolean {
  const id = e.attrs.id ?? "";
  return /^(?:wm-ipp|donato|wm-capinfo)/i.test(id);
}

// The tree with the furniture pruned (a copy; the input is untouched).
function prune(el: HtmlElement, inArticle = false): HtmlElement {
  const children: HtmlNode[] = [];
  for (const c of el.children) {
    if (!isEl(c)) {
      children.push(c);
      continue;
    }
    if (DROP_TAGS.has(c.tag) || isHidden(c) || isWaybackChrome(c)) continue;
    if (DROP_ROLES.has((c.attrs.role ?? "").toLowerCase())) continue;
    if (c.tag === "footer") continue;
    if (c.tag === "header" && !inArticle) continue;
    children.push(prune(c, inArticle || c.tag === "article"));
  }
  return { tag: el.tag, attrs: el.attrs, children };
}

// ─── Main content ───

const CANDIDATE_TAGS = new Set(["div", "section", "td", "body", "article", "main", "#root", "center", "font", "span"]);
const PARAGRAPH_TAGS = new Set(["p", "pre", "blockquote"]);

function linkDensity(el: HtmlElement): number {
  const all = collapse(rawText(el)).length;
  if (all === 0) return 0;
  let linked = 0;
  for (const a of findAll(el, (e) => e.tag === "a", false)) linked += collapse(rawText(a)).length;
  return Math.min(1, linked / all);
}

function pickMain(root: HtmlElement): HtmlElement[] {
  const main = first(root, (e) => e.tag === "main" || (e.attrs.role ?? "").toLowerCase() === "main");
  if (main) return [main];
  const articles = findAll(root, (e) => e.tag === "article", false);
  if (articles.length > 0) return articles;
  const parent = new Map<HtmlElement, HtmlElement>();
  const order: HtmlElement[] = [];
  const scores = new Map<HtmlElement, number>();
  walk(root, (e, p) => {
    parent.set(e, p);
    order.push(e);
  });
  for (const e of order) {
    if (!PARAGRAPH_TAGS.has(e.tag)) continue;
    const text = collapse(rawText(e));
    if (text.length < 25) continue;
    const score = 1 + (text.match(/,/g)?.length ?? 0) + Math.min(Math.floor(text.length / 100), 3);
    const p = parent.get(e);
    if (p && CANDIDATE_TAGS.has(p.tag)) scores.set(p, (scores.get(p) ?? 0) + score);
    const g = p ? parent.get(p) : undefined;
    if (g && CANDIDATE_TAGS.has(g.tag)) scores.set(g, (scores.get(g) ?? 0) + score / 2);
  }
  let best: HtmlElement | null = null;
  let bestScore = 0;
  // Document order, and a strict `>`: the first of equal scores wins.
  for (const e of [root, ...order]) {
    const s = scores.get(e);
    if (s === undefined) continue;
    const final = s * (1 - linkDensity(e));
    if (final > bestScore) {
      best = e;
      bestScore = final;
    }
  }
  if (best) return [best];
  const body = first(root, (e) => e.tag === "body");
  return [body ?? root];
}

// ─── Text ───

const BLOCK_TAGS = new Set([
  "p", "div", "section", "article", "main", "header", "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "li",
  "blockquote", "pre", "table", "thead", "tbody", "tr", "dl", "dt", "dd", "figure", "figcaption", "address",
  "hr", "center", "body", "#root",
]);

type Ctx = { blocks: string[]; line: string[] };

function flush(ctx: Ctx): void {
  const t = collapse(ctx.line.join(""));
  if (t) ctx.blocks.push(t);
  ctx.line = [];
}

function renderChildren(el: HtmlElement, ctx: Ctx): void {
  for (const c of el.children) renderNode(c, ctx);
}

function sub(el: HtmlElement): string[] {
  const ctx: Ctx = { blocks: [], line: [] };
  renderChildren(el, ctx);
  flush(ctx);
  return ctx.blocks;
}

function renderNode(n: HtmlNode, ctx: Ctx): void {
  if (!isEl(n)) {
    ctx.line.push(n);
    return;
  }
  switch (n.tag) {
    case "br":
      flush(ctx);
      return;
    case "img": {
      const alt = collapse(n.attrs.alt ?? "");
      if (alt) ctx.line.push(` [Image: ${alt}] `);
      return;
    }
    case "pre": {
      flush(ctx);
      const t = rawText(n).replace(/\r\n?/g, "\n").replace(/^\n+|\s+$/g, "");
      if (t) ctx.blocks.push(t);
      return;
    }
    case "li": {
      flush(ctx);
      const t = sub(n).join(" ");
      if (t) ctx.blocks.push(`- ${t}`);
      return;
    }
    case "blockquote": {
      flush(ctx);
      for (const b of sub(n)) ctx.blocks.push(b.split("\n").map((l) => `> ${l}`).join("\n"));
      return;
    }
    case "td":
    case "th":
      renderChildren(n, ctx);
      ctx.line.push(" ");
      return;
  }
  if (BLOCK_TAGS.has(n.tag)) {
    flush(ctx);
    renderChildren(n, ctx);
    flush(ctx);
    return;
  }
  renderChildren(n, ctx);
}

function renderText(nodes: HtmlElement[]): string {
  const blocks: string[] = [];
  for (const n of nodes) {
    const ctx: Ctx = { blocks: [], line: [] };
    renderNode(n, ctx);
    flush(ctx);
    blocks.push(...ctx.blocks);
  }
  return blocks.join("\n\n");
}

// ─── Metadata ───

type Meta = Map<string, string>;

function readMeta(root: HtmlElement): Meta {
  const meta: Meta = new Map();
  walk(root, (e) => {
    if (e.tag !== "meta") return;
    const key = (e.attrs.property ?? e.attrs.name ?? e.attrs.itemprop ?? "").trim().toLowerCase();
    const content = collapse(e.attrs.content ?? "");
    if (key && content && !meta.has(key)) meta.set(key, content);
  });
  return meta;
}

const JSON_LD_RE = /<script\b[^>]*\btype\s*=\s*["']?application\/ld\+json["']?[^>]*>([\s\S]*?)<\/script\s*>/gi;

type LdFacts = { author?: string; datePublished?: string; headline?: string };

function readJsonLd(html: string): LdFacts {
  const out: LdFacts = {};
  const nameOf = (a: unknown): string | undefined => {
    if (typeof a === "string") return collapse(a) || undefined;
    if (Array.isArray(a)) return a.map(nameOf).find(Boolean);
    if (a && typeof a === "object") return nameOf((a as Record<string, unknown>).name);
    return undefined;
  };
  const visit = (v: unknown): void => {
    if (Array.isArray(v)) return v.forEach(visit);
    if (!v || typeof v !== "object") return;
    const o = v as Record<string, unknown>;
    if (!out.datePublished && typeof o.datePublished === "string") out.datePublished = o.datePublished;
    if (!out.author && o.author !== undefined) out.author = nameOf(o.author);
    if (!out.headline && typeof o.headline === "string") out.headline = collapse(o.headline) || undefined;
    if (o["@graph"]) visit(o["@graph"]);
  };
  for (const m of html.matchAll(JSON_LD_RE)) {
    try {
      visit(JSON.parse(m[1].trim()));
    } catch {
      // A malformed block says nothing.
    }
  }
  return out;
}

// A date the page gives, as ISO-8601, or undefined: unparseable, or after the
// capture (a page cannot have been written after it was captured; a
// "modified" date some templates fill with the render time is not believed).
function believableDate(raw: string | undefined, captureTs: string): string | undefined {
  if (!raw) return undefined;
  const ms = Date.parse(raw.trim());
  if (!Number.isFinite(ms)) return undefined;
  const cap = Date.parse(captureTsIso(captureTs));
  if (Number.isFinite(cap) && ms > cap + 24 * 3600 * 1000) return undefined;
  if (ms < Date.UTC(1990, 0, 1)) return undefined;
  return new Date(ms).toISOString();
}

const isUrlish = (s: string) => /^https?:\/\//i.test(s);

// ─── The extractor ───

export function extractGeneric(input: PageExtractInput): PageRecordDraft {
  const { capture } = input;
  const mime = bareMimetype(capture.mimetype);
  if (mime === "text/plain" || mime === "application/json") {
    const text = input.html.replace(/\r\n?/g, "\n").trim();
    return text
      ? { kind: "generic", text, links: [] }
      : { kind: "generic", text: NO_CONTENT_TEXT, links: [], noContent: true };
  }
  const html = stripWaybackChrome(input.html);
  const root = parseHtml(html);
  const meta = readMeta(root);
  const ld = readJsonLd(html);

  const titleEl = first(root, (e) => e.tag === "title");
  const h1 = first(root, (e) => e.tag === "h1");
  const title =
    meta.get("og:title") ??
    (titleEl ? collapse(rawText(titleEl)) || undefined : undefined) ??
    (h1 ? collapse(rawText(h1)) || undefined : undefined) ??
    ld.headline;

  const pruned = prune(root);
  const main = pickMain(pruned);

  const authorCandidates = [
    ld.author,
    meta.get("author"),
    meta.get("article:author"),
    meta.get("dc.creator"),
    meta.get("twitter:creator"),
  ].filter((a): a is string => !!a && !isUrlish(a));
  const author = authorCandidates[0];

  let timeAttr: string | undefined;
  for (const n of main) {
    const t = first(n, (e) => e.tag === "time" && !!e.attrs.datetime);
    if (t) {
      timeAttr = t.attrs.datetime;
      break;
    }
  }
  const dateCandidates = [
    meta.get("article:published_time"),
    meta.get("og:published_time"),
    meta.get("datepublished"),
    meta.get("date"),
    meta.get("pubdate"),
    meta.get("publishdate"),
    meta.get("dc.date.issued"),
    meta.get("dc.date"),
    ld.datePublished,
    timeAttr,
  ];
  let publishedAt: string | undefined;
  for (const d of dateCandidates) {
    publishedAt = believableDate(d, capture.captureTs);
    if (publishedAt) break;
  }

  let text = renderText(main);
  if (title && text && !collapse(text.slice(0, title.length + 20)).startsWith(collapse(title))) {
    text = `${title}\n\n${text}`;
  }

  const links: string[] = [];
  const seenLinks = new Set<string>();
  const media: PostMedia[] = [];
  const seenMedia = new Set<string>();
  for (const n of main) {
    walk(n, (e) => {
      if (e.tag === "a" && links.length < MAX_LINKS) {
        const abs = absoluteOriginalUrl(e.attrs.href, capture.originalUrl);
        if (abs && !seenLinks.has(abs)) {
          seenLinks.add(abs);
          links.push(abs);
        }
      }
      if (e.tag === "img" && media.length < MAX_MEDIA) {
        const abs = absoluteOriginalUrl(e.attrs.src ?? e.attrs["data-src"], capture.originalUrl);
        if (abs && !seenMedia.has(abs)) {
          seenMedia.add(abs);
          const alt = collapse(e.attrs.alt ?? "");
          media.push({ kind: "image", url: waybackImageUrl(capture.captureTs, abs), ...(alt ? { name: alt } : {}) });
        }
      }
    });
  }

  const draft: PageRecordDraft = {
    kind: "generic",
    text: text || NO_CONTENT_TEXT,
    links,
  };
  if (!text) draft.noContent = true;
  if (title) draft.title = title;
  // A page's author is a name, not a handle: `author` alone (a reader shows
  // "@author" only beside an authorName).
  if (author) draft.author = author.replace(/^@/, "");
  if (publishedAt) draft.publishedAt = publishedAt;
  if (media.length > 0) draft.media = media;
  return draft;
}

export const genericExtractor: PageExtractor = {
  name: GENERIC_EXTRACTOR_NAME,
  version: GENERIC_EXTRACTOR_VERSION,
  matches: () => true,
  extract: (input) => [extractGeneric(input)],
};