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 stripHtml(html) {
  return html.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
}
function toEpochSeconds(iso) {
  const t = new Date(iso).getTime();
  if (isNaN(t)) return void 0;
  return Math.floor(t / 1e3);
}
class StackOverflowEngine {
  name = "stackoverflow";
  async search(query, options = {}) {
    const timeoutMs = options.timeoutMs ?? 1e4;
    const maxResults = options.maxResults ?? 10;
    const params = new URLSearchParams({
      order: "desc",
      sort: "relevance",
      q: query,
      site: "stackoverflow",
      filter: "withbody",
      pagesize: String(maxResults)
    });
    if (options.fromDate) {
      const epoch = toEpochSeconds(options.fromDate);
      if (epoch !== void 0) params.set("fromdate", String(epoch));
    }
    if (options.toDate) {
      const epoch = toEpochSeconds(options.toDate);
      if (epoch !== void 0) params.set("todate", String(epoch));
    }
    const url = `https://api.stackexchange.com/2.3/search/advanced?${params}`;
    log.debug("stackoverflow search", { query });
    const response = await fetch(url, { signal: AbortSignal.timeout(timeoutMs) });
    if (!response.ok) throw new Error(`StackOverflow returned ${response.status}`);
    const data = await response.json();
    return this.parseItems(data.items ?? []);
  }
  parseItems(items) {
    const results = [];
    const total = items.length;
    for (let i = 0; i < total; i++) {
      const item = items[i];
      const title = asString(item.title);
      const link = asString(item.link);
      if (!title || !link) continue;
      const bodyHtml = asString(item.body) ?? "";
      const snippet = stripHtml(bodyHtml).slice(0, SNIPPET_LIMIT);
      const createdAt = asNumber(item.creation_date);
      const published_date = createdAt ? new Date(createdAt * 1e3).toISOString() : void 0;
      results.push({
        title,
        url: link,
        snippet,
        relevance_score: 1 - i / Math.max(total, 1),
        engine: "stackoverflow",
        ...published_date ? { published_date } : {}
      });
    }
    return results;
  }
}
export {
  StackOverflowEngine
};
//# sourceMappingURL=stackoverflow.js.map