import { getSearxngURL } from './config/serverRegistry';

interface SearxngSearchOptions {
  categories?: string[];
  engines?: string[];
  language?: string;
  pageno?: number;
}

interface SearxngSearchResult {
  title: string;
  url: string;
  img_src?: string;
  thumbnail_src?: string;
  thumbnail?: string;
  content?: string;
  author?: string;
  iframe_src?: string;
}

export const searchSearxng = async (
  query: string,
  opts?: SearxngSearchOptions,
) => {
  const searxngURL = getSearxngURL();

  if (!searxngURL?.trim()) {
    throw new Error(
      'SearxNG is not configured. Please set the SearxNG URL in Settings → Search.',
    );
  }

  let baseUrl = searxngURL.trim().replace(/\/$/, '');
  if (!/^https?:\/\//i.test(baseUrl)) {
    baseUrl = `http://${baseUrl}`;
  }

  const url = new URL(`${baseUrl}/search?format=json`);
  url.searchParams.append('q', query);

  if (opts) {
    Object.keys(opts).forEach((key) => {
      const value = opts[key as keyof SearxngSearchOptions];
      if (Array.isArray(value)) {
        url.searchParams.append(key, value.join(','));
        return;
      }
      url.searchParams.append(key, value as string);
    });
  }

  const res = await fetch(url);
  const text = await res.text();

  const contentType = res.headers.get('content-type') ?? '';
  const isJson =
    contentType.includes('application/json') ||
    text.trim().startsWith('{') ||
    text.trim().startsWith('[');

  if (!isJson) {
    throw new Error(
      'SearxNG returned HTML instead of JSON. Check that the URL includes http:// or https:// (e.g. http://localhost:4000) and that SearxNG is running.',
    );
  }

  const data = JSON.parse(text);
  const results: SearxngSearchResult[] = data.results ?? [];
  const suggestions: string[] = data.suggestions ?? [];

  return { results, suggestions };
};
