import { createLogger } from "../../logger.js";
import { getConfig } from "../../config.js";
const log = createLogger("search");
function asString(v) {
  return typeof v === "string" && v.length > 0 ? v : void 0;
}
class GithubCodeEngine {
  name = "github-code";
  async search(query, options = {}) {
    const timeoutMs = options.timeoutMs ?? 1e4;
    const maxResults = options.maxResults ?? 10;
    const params = new URLSearchParams({
      q: query,
      per_page: String(maxResults)
    });
    const url = `https://api.github.com/search/code?${params}`;
    log.debug("github code search", { query });
    const headers = {
      Accept: "application/vnd.github+json",
      "X-GitHub-Api-Version": "2022-11-28"
    };
    const token = getConfig().githubToken;
    if (token) headers.Authorization = `Bearer ${token}`;
    const response = await fetch(url, {
      signal: AbortSignal.timeout(timeoutMs),
      headers
    });
    if (response.status === 403) {
      throw new Error(`GitHub code rate-limited (${response.status})`);
    }
    if (!response.ok) {
      throw new Error(`GitHub code 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 repoName = asString(item.repository?.full_name);
      const path = asString(item.path);
      const htmlUrl = asString(item.html_url);
      if (!repoName || !path || !htmlUrl) continue;
      const description = asString(item.repository?.description);
      const snippet = description ? `${description} \u2014 ${path}` : path;
      results.push({
        title: `${repoName} \u2014 ${path}`,
        url: htmlUrl,
        snippet,
        relevance_score: 1 - i / Math.max(total, 1),
        engine: "github-code"
      });
    }
    return results;
  }
}
export {
  GithubCodeEngine
};
//# sourceMappingURL=github-code.js.map