// Pure outbound-link builders. NO network here — these only construct URLs.
// Privacy: the only data placed in a URL is the extracted citation value or a
// resolved title — never transcript text. Anna's Archive / LibGen appear as
// SEARCH urls only; nothing in this app fetches or proxies them.

import type { Citation, LookupLinks, RefMetadata } from './types';

/** Build lookup links for a detected citation, optionally enriched by metadata. */
export function lookupLinksFor(c: Citation, meta?: RefMetadata): LookupLinks {
  const query = (meta?.title || c.value).trim();

  const links: LookupLinks = {
    ...searchLinks(query),
  };

  if (c.kind === 'doi') {
    links.doi = `https://doi.org/${encodeURIComponent(c.value)}`;
  }
  if (c.kind === 'arxiv') {
    links.arxiv = `https://arxiv.org/abs/${encodeURIComponent(c.value)}`;
  }
  if (c.kind === 'isbn') {
    // Direct ISBN page beats a free-text Open Library search.
    links.openLibrary = `https://openlibrary.org/isbn/${encodeURIComponent(
      c.value,
    )}`;
  }

  return links;
}

/** Build the same set of links from a free-text query (no DOI/arXiv). */
export function bookLinksFor(query: string): LookupLinks {
  return searchLinks(query.trim());
}

/** The query-driven search links shared by both entry points. */
function searchLinks(query: string): LookupLinks {
  const q = encodeURIComponent(query);
  return {
    wikipedia: `https://en.wikipedia.org/wiki/Special:Search?search=${q}`,
    googleBooks: `https://www.google.com/search?tbm=bks&q=${q}`,
    openLibrary: `https://openlibrary.org/search?q=${q}`,
    annasArchive: `https://annas-archive.org/search?q=${q}`,
    libgen: `https://libgen.is/search.php?req=${q}`,
  };
}
