// One-shot diagnostic: run the same esearch + efetch that the studies cache
// runs from inside the Next.js server, and print whatever actually happens.
// Runs against the real PubMed eutils endpoint over Node's global fetch.

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]',
  '"Clin Orthop Relat Res"[Journal]',
  '"Spine (Phila Pa 1976)"[Journal]',
  '"Foot Ankle Int"[Journal]',
  '"Orthop J Sports Med"[Journal]',
  '"J Orthop Res"[Journal]',
  '"Osteoarthritis Cartilage"[Journal]',
  '"Knee Surg Sports Traumatol Arthrosc"[Journal]',
  '"J Shoulder Elbow Surg"[Journal]',
].join(" OR ");
const FULL_TERM = `(${TERM}) AND ("last 180 days"[PDat])`;

function buildUrl(path, params) {
  const qs = new URLSearchParams({ ...POLITE, ...params });
  return `${EUTILS_BASE}/${path}?${qs.toString()}`;
}

async function run() {
  console.log("NODE_VERSION:", process.version);
  console.log("PLATFORM:", process.platform);

  const esearchUrl = buildUrl("esearch.fcgi", {
    db: "pubmed",
    term: FULL_TERM,
    retmode: "json",
    retmax: "5",
    sort: "pub_date",
  });
  console.log("\n-- esearch --");
  console.log("URL:", esearchUrl.slice(0, 140) + "...");

  let esearchRes;
  try {
    esearchRes = await fetch(esearchUrl);
  } catch (err) {
    console.error("esearch fetch threw:", err?.message ?? err);
    console.error("cause:", err?.cause?.code ?? err?.cause);
    process.exit(1);
  }
  console.log("status:", esearchRes.status, esearchRes.statusText);

  const esearchText = await esearchRes.text();
  console.log("body (first 400 chars):", esearchText.slice(0, 400));

  let esearchJson;
  try {
    esearchJson = JSON.parse(esearchText);
  } catch (err) {
    console.error("esearch JSON parse failed:", err?.message);
    process.exit(1);
  }
  const ids = esearchJson?.esearchresult?.idlist ?? [];
  console.log("idlist length:", ids.length);
  console.log("first ids:", ids.slice(0, 5));

  if (ids.length === 0) {
    console.log("\n❌ esearch returned zero PMIDs — stopping.");
    process.exit(0);
  }

  console.log("\n-- efetch --");
  const efetchUrl = buildUrl("efetch.fcgi", {
    db: "pubmed",
    id: ids.slice(0, 3).join(","),
    retmode: "xml",
    rettype: "abstract",
  });
  console.log("URL:", efetchUrl.slice(0, 140) + "...");

  let efetchRes;
  try {
    efetchRes = await fetch(efetchUrl);
  } catch (err) {
    console.error("efetch fetch threw:", err?.message ?? err);
    console.error("cause:", err?.cause?.code ?? err?.cause);
    process.exit(1);
  }
  console.log("status:", efetchRes.status, efetchRes.statusText);

  const xml = await efetchRes.text();
  console.log("xml length:", xml.length);
  console.log("xml head (first 400 chars):", xml.slice(0, 400));

  console.log("\n✅ diagnostic complete.");
}

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