// End-to-end smoke test that mirrors the full fetch → parse flow with the
// FIXED asString helper. If this prints a non-zero count with real PMIDs
// and titles, the studies page will populate on the next request.

import { XMLParser } from "fast-xml-parser";

const EUTILS_BASE = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils";
const POLITE = { tool: "orthoglobe", email: "contact@orthoglobe.org" };
const TERM = [
  '"J Bone Joint Surg Am"[Journal]',
  '"Bone Joint J"[Journal]',
  '"Am J Sports Med"[Journal]',
  '"Arthroscopy"[Journal]',
  '"J Shoulder Elbow Surg"[Journal]',
].join(" OR ");
const FULL_TERM = `(${TERM}) AND ("last 180 days"[PDat])`;

function asRecord(v) {
  return typeof v === "object" && v !== null ? v : undefined;
}
function asArray(v) {
  if (v == null) return [];
  return Array.isArray(v) ? v : [v];
}
// Fixed version: handles both string and number #text
function asString(v) {
  if (v == null) return "";
  if (typeof v === "string") return v;
  if (typeof v === "number") return String(v);
  const rec = asRecord(v);
  const text = rec?.["#text"];
  if (typeof text === "string") return text;
  if (typeof text === "number") return String(text);
  return "";
}

async function run() {
  const esearchUrl = `${EUTILS_BASE}/esearch.fcgi?${new URLSearchParams({
    ...POLITE,
    db: "pubmed",
    term: FULL_TERM,
    retmode: "json",
    retmax: "10",
    sort: "pub_date",
  })}`;
  const ids = (await (await fetch(esearchUrl)).json()).esearchresult.idlist;

  const efetchUrl = `${EUTILS_BASE}/efetch.fcgi?${new URLSearchParams({
    ...POLITE,
    db: "pubmed",
    id: ids.join(","),
    retmode: "xml",
    rettype: "abstract",
  })}`;
  const xml = await (await fetch(efetchUrl)).text();

  const parser = new XMLParser({
    ignoreAttributes: false,
    attributeNamePrefix: "@_",
    textNodeName: "#text",
    trimValues: true,
  });
  const parsed = parser.parse(xml);
  const articles = asArray(parsed?.PubmedArticleSet?.PubmedArticle);

  let kept = 0;
  let dropped = 0;
  for (const art of articles) {
    const medline = asRecord(art?.MedlineCitation);
    const pmid = asString(medline?.PMID);
    if (!pmid) {
      dropped += 1;
      continue;
    }
    const article = asRecord(medline?.Article);
    const title = asString(article?.ArticleTitle);
    if (!title) {
      dropped += 1;
      continue;
    }
    kept += 1;
    if (kept <= 3) {
      console.log(`✓ PMID=${pmid}  ${title.slice(0, 70)}`);
    }
  }

  console.log(`\ntotal articles from PubMed: ${articles.length}`);
  console.log(`kept: ${kept}`);
  console.log(`dropped: ${dropped}`);
  if (kept === 0) {
    console.log("\n❌ parser still drops every article — fix not complete.");
    process.exit(1);
  }
  console.log("\n✅ parser produces usable studies.");
}

run().catch((err) => {
  console.error(err);
  process.exit(1);
});
