export type SearxResult = { title: string; url: string; snippet?: string; engine?: string };

const safeUrlOrNull = (value: unknown) => {
  const s = typeof value === "string" ? value.trim() : "";
  if (!s) return null;
  try {
    const u = new URL(s);
    if (u.protocol !== "http:" && u.protocol !== "https:") return null;
    return u.toString();
  } catch {
    return null;
  }
};

export const searchSearxng = async (q: string, count = 6): Promise<SearxResult[]> => {
  const query = String(q || "").trim();
  if (!query) return [];

  const base = (process.env.SEARXNG_BASE_URL ?? "http://127.0.0.1:8889").replace(/\/+$/, "");
  const token = (process.env.SEARXNG_API_TOKEN ?? "").trim();
  const url = `${base}/search?q=${encodeURIComponent(query)}&format=json&language=zhh-CN&categories=general&safesearch=1`;

  const tryFetch = async (headers: Record<string, string>) => {
    const res = await fetch(url, { headers, method: "GET" });
    if (!res.ok) return null;
    return (await res.json().catch(() => null)) as unknown;
  };

  let json: unknown = null;
  if (token) {
    json = (await tryFetch({ Authorization: `Bearer ${token}` })) ?? (await tryFetch({ "X-API-Key": token })) ?? null;
  }
  if (!json) json = await tryFetch({});

  const results = (() => {
    if (typeof json !== "object" || !json) return [];
    const obj = json as Record<string, unknown>;
    const value = obj.results;
    return Array.isArray(value) ? (value as unknown[]) : [];
  })();
  const normalized = results
    .map((r: unknown) => {
      const obj = (typeof r === "object" && r ? (r as Record<string, unknown>) : {}) as Record<string, unknown>;
      return {
        title: String(obj.title ?? "").trim(),
        url: String(obj.url ?? "").trim(),
        snippet: String(obj.content ?? obj.snippet ?? "").trim(),
        engine: String(obj.engine ?? "").trim(),
      };
    })
      .filter((r: SearxResult) => r.title && safeUrlOrNull(r.url))
      .slice(0, Math.max(1, Math.min(10, count)));
  return normalized;
};
