import { createLogger } from "../../logger.js";
const log = createLogger("search");
const SNIPPET_LIMIT = 200;
function asString(v) {
  return typeof v === "string" && v.length > 0 ? v : void 0;
}
function asNumber(v) {
  return typeof v === "number" && isFinite(v) ? v : void 0;
}
function yearOf(iso) {
  const t = new Date(iso).getTime();
  if (isNaN(t)) return void 0;
  return new Date(t).getUTCFullYear();
}
class SemanticScholarEngine {
  name = "semantic-scholar";
  async search(query, options = {}) {
    const timeoutMs = options.timeoutMs ?? 1e4;
    const maxResults = options.maxResults ?? 10;
    const params = new URLSearchParams({
      query,
      limit: String(maxResults),
      fields: "title,abstract,year,url,authors,externalIds,openAccessPdf"
    });
    if (options.fromDate || options.toDate) {
      const fromY = options.fromDate ? yearOf(options.fromDate) : void 0;
      const toY = options.toDate ? yearOf(options.toDate) : void 0;
      if (fromY !== void 0 || toY !== void 0) {
        params.set("year", `${fromY ?? ""}-${toY ?? ""}`);
      }
    }
    const url = `https://api.semanticscholar.org/graph/v1/paper/search?${params}`;
    log.debug("semantic-scholar search", { query });
    const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
    if (!response.ok) throw new Error(`Semantic Scholar returned ${response.status}`);
    const data = await response.json();
    return this.parsePapers(data.data ?? []);
  }
  parsePapers(papers) {
    const results = [];
    const total = papers.length;
    for (let i = 0; i < total; i++) {
      const p = papers[i];
      const title = asString(p.title);
      if (!title) continue;
      const pdfUrl = asString(p.openAccessPdf?.url);
      const baseUrl = asString(p.url);
      const url = pdfUrl ?? baseUrl;
      if (!url) continue;
      const abstract = asString(p.abstract) ?? "";
      const snippet = abstract.slice(0, SNIPPET_LIMIT);
      const year = asNumber(p.year);
      const published_date = year ? `${year}-01-01T00:00:00.000Z` : void 0;
      results.push({
        title,
        url,
        snippet,
        relevance_score: 1 - i / Math.max(total, 1),
        engine: "semantic-scholar",
        ...published_date ? { published_date } : {}
      });
    }
    return results;
  }
}
export {
  SemanticScholarEngine
};
//# sourceMappingURL=semantic-scholar.js.map