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 extractHits(data) {
  if (Array.isArray(data)) return data;
  if (data && typeof data === "object" && "results" in data) {
    const r = data.results;
    if (Array.isArray(r)) return r;
  }
  return [];
}
class LobstersEngine {
  name = "lobsters";
  async search(query, options = {}) {
    const timeoutMs = options.timeoutMs ?? 1e4;
    const maxResults = options.maxResults ?? 10;
    const params = new URLSearchParams({ q: query, what: "stories" });
    const url = `https://lobste.rs/search.json?${params}`;
    log.debug("lobsters search", { query });
    const response = await fetch(url, {
      signal: AbortSignal.timeout(timeoutMs),
      headers: {
        Accept: "application/json",
        "User-Agent": "wigolo/0.1 (https://github.com/staticn0va/wigolo)"
      }
    });
    if (!response.ok) throw new Error(`Lobsters returned ${response.status}`);
    const data = await response.json();
    const hits = extractHits(data);
    const mapped = this.parseHits(hits);
    const filtered = applyDateFilter(mapped, options);
    return filtered.slice(0, maxResults);
  }
  parseHits(hits) {
    const results = [];
    const total = hits.length;
    for (let i = 0; i < total; i++) {
      const hit = hits[i];
      const title = asString(hit.title);
      if (!title) continue;
      const url = asString(hit.url) ?? asString(hit.short_id_url);
      if (!url) continue;
      const description = asString(hit.description);
      const score = asNumber(hit.score) ?? 0;
      const comments = asNumber(hit.comment_count) ?? 0;
      const snippet = description ? description.slice(0, SNIPPET_LIMIT) : `${score} score \xB7 ${comments} comments`;
      const createdAt = asString(hit.created_at);
      let published_date;
      if (createdAt) {
        const d = new Date(createdAt);
        if (!isNaN(d.getTime())) published_date = d.toISOString();
      }
      results.push({
        title,
        url,
        snippet,
        relevance_score: 1 - i / Math.max(total, 1),
        engine: "lobsters",
        ...published_date ? { published_date } : {}
      });
    }
    return results;
  }
}
function applyDateFilter(results, options) {
  if (!options.fromDate && !options.toDate) return results;
  const from = options.fromDate ? new Date(options.fromDate).getTime() : -Infinity;
  const to = options.toDate ? new Date(options.toDate).getTime() : Infinity;
  if (isNaN(from) || isNaN(to)) return results;
  return results.filter((r) => {
    if (!r.published_date) return false;
    const t = new Date(r.published_date).getTime();
    if (isNaN(t)) return false;
    return t >= from && t <= to;
  });
}
export {
  LobstersEngine
};
//# sourceMappingURL=lobsters.js.map