/* Rank Lyx — AI Research Agent / EXTERNAL SOURCE RETRIEVAL layer (v1)
   ------------------------------------------------------------------------------
   Turns the web into a controlled list of sourceCandidates the Research LLM is
   allowed to cite. It does NOT let the LLM browse, does NOT invent sources, and
   does NOT create final notes. The division of labour is strict:

       retrieval layer  → FINDS possible sources (this file)
       Research LLM      → CHOOSES what to use
       validation layer  → DECIDES what can be saved

   Provider-neutral by design: it calls a `searchProvider` and an optional
   `fetchProvider` that the host wires to a BACKEND function. No vendor is named,
   no API key lives here, and no paid search API is called directly from the
   browser. Search/fetch failures degrade gracefully to internal candidates + a
   warning — they never crash the workflow.

   Portability: every function is pure-ish and exported on window.ResearchAgent /
   window.ResearchNotes today, but is written so it can move into ES modules in a
   Lovable/React app later with no behavioural change.

   Load AFTER research.jsx, research-validation.jsx, research-notes.jsx, research-llm.jsx.
*/

(function () {
  const RA = window.ResearchAgent || (window.ResearchAgent = {});
  const RN = window.ResearchNotes || (window.ResearchNotes = {});

  const RESEARCH_SOURCE_CANDIDATE_VERSION = 1;

  /* ---- tunables (constants, easy to lift into config later) ---- */
  const LIMITS = {
    maxQueries: 12,
    maxResultsPerQuery: 4,
    maxTotalCandidates: 40,
    maxCommunity: 8,
    maxCompetitor: 8,        // only for comparison-style articles
    maxInternal: 10,
    maxExternalNonCommunity: 25,
    excerptMaxChars: 800
  };

  const COMPARISON_POST_TYPES =
    /(comparison|roundup|alternatives?|best\s+(tools|software|apps)|vs\b|versus|pricing\s+comparison)/i;

  const clean = (s) => (s == null ? '' : String(s)).trim();
  const lc = (s) => clean(s).toLowerCase();
  const isComparisonArticle = (ac) => COMPARISON_POST_TYPES.test(lc(ac && ac.postType));

  /* ============================================================================
     1 — QUERY PLANNING
     Build a controlled set of discovery queries from neutral article context.
     This finds SOURCES; it never assigns a note type to any section.
  ============================================================================ */
  function buildResearchSearchQueries({ ctx, payload }) {
    const ac = (payload && payload.articleContext) || (ctx && ctx.articleContext) || {};
    const oc = (payload && payload.outline) || (ctx && ctx.outlineContext) || {};
    const eligible = oc.eligibleSections || [];

    const topic = clean(ac.topic);
    const kw = clean(ac.primaryKeyword) || topic;
    const comparison = isComparisonArticle(ac);

    const queries = [];
    const seen = new Set();
    const add = (q) => {
      const t = clean(q);
      if (!t) return;
      const key = lc(t).replace(/\s+/g, ' ');
      if (seen.has(key)) return;
      seen.add(key);
      queries.push(t);
    };

    /* core discovery — statistics, reports, benchmarks, trends */
    if (kw) {
      add(kw + ' statistics report');
      add(kw + ' industry report');
      add(kw + ' benchmark report');
      add(kw + ' survey');
      add(kw + ' trends');
    }
    if (topic && lc(topic) !== lc(kw)) {
      add(topic + ' statistics');
      add(topic + ' trends');
    }

    /* user signal / pain points (community) */
    if (kw) {
      add(kw + ' pain points Reddit');
      add(kw + ' Quora');
    }

    /* official product / pricing — ONLY for comparison-style articles */
    if (comparison) {
      const subject = topic || kw;
      add(subject + ' pricing');
      add(subject + ' official pricing');
    }

    /* one eligible-section-led query for specificity, if room */
    if (eligible.length && queries.length < LIMITS.maxQueries) {
      const titled = eligible.find((s) => clean(s.headingTitle) && !s.isIntro);
      if (titled) add(clean(titled.headingTitle) + ' ' + (kw || '') + ' data');
    }

    return queries.slice(0, LIMITS.maxQueries);
  }

  /* ============================================================================
     2 — NORMALIZE SEARCH RESULTS
     Accept whatever a provider returns and coerce to the documented result shape.
  ============================================================================ */
  function normalizeSearchResults(raw) {
    /* tolerate: { results: [...] } | [...] | { data: [...] } | { items: [...] } */
    let list = [];
    if (Array.isArray(raw)) list = raw;
    else if (raw && Array.isArray(raw.results)) list = raw.results;
    else if (raw && Array.isArray(raw.data)) list = raw.data;
    else if (raw && Array.isArray(raw.items)) list = raw.items;

    const out = [];
    list.forEach((r) => {
      if (!r) return;
      const url = clean(r.url || r.link || r.href);
      if (!url) return;
      out.push({
        query: clean(r.query) || null,
        title: clean(r.title || r.name) || url,
        url: url,
        snippet: clean(r.snippet || r.description || r.text || r.content || r.raw_content || r.rawContent),
        rawContent: clean(r.raw_content || r.rawContent || r.content),
        publisher: clean(r.publisher || r.source || r.site || domainOf(url)) || null,
        publishedDate: normalizeDate(r.publishedDate || r.published || r.date || r.datePublished),
        updatedDate: normalizeDate(r.updatedDate || r.updated || r.dateModified)
      });
    });
    return out;
  }

  function domainOf(url) {
    try {
      const u = new URL(url);
      return u.hostname.replace(/^www\./, '');
    } catch (e) {
      const m = clean(url).match(/^https?:\/\/(?:www\.)?([^\/]+)/i);
      return m ? m[1] : '';
    }
  }

  /* keep only a reliable date; prefer full ISO, else a bare year. Never invent. */
  function normalizeDate(d) {
    const s = clean(d);
    if (!s) return null;
    const iso = s.match(/\b(19|20)\d{2}-\d{2}-\d{2}\b/);
    if (iso) return iso[0];
    const ym = s.match(/\b(19|20)\d{2}-\d{2}\b/);
    if (ym) return ym[0];
    const yr = s.match(/\b(19|20)\d{2}\b/);
    if (yr) return yr[0];
    return null;
  }
  function detectYear(text) {
    const m = clean(text).match(/\b(20\d{2})\b/g);
    if (!m) return null;
    /* prefer the most recent plausible year present */
    const years = m.map(Number).filter((y) => y >= 2015 && y <= 2030);
    return years.length ? String(Math.max.apply(null, years)) : null;
  }

  /* ============================================================================
     3 — OPTIONAL PAGE FETCH
     Enrich results with page text/date via a provider-neutral fetchProvider.
     Optional, best-effort, never throws upward.
  ============================================================================ */
  async function fetchSearchResultDetails({ results, fetchProvider, meta, warnings }) {
    warnings = warnings || [];
    if (typeof fetchProvider !== 'function') {
      return results.map((r) => ({ result: r, fetchedPage: null }));
    }
    const out = [];
    for (let i = 0; i < results.length; i++) {
      const r = results[i];
      let fetchedPage = null;
      try {
        const raw = await fetchProvider({
          url: r.url,
          metadata: { articleId: meta.articleId, workspaceId: meta.workspaceId, task: 'fetch_research_source_candidate' }
        });
        if (raw) {
          fetchedPage = {
            url: clean(raw.url) || r.url,
            title: clean(raw.title) || r.title,
            publisher: clean(raw.publisher) || r.publisher,
            publishedDate: normalizeDate(raw.publishedDate) || r.publishedDate,
            updatedDate: normalizeDate(raw.updatedDate) || r.updatedDate,
            text: clean(raw.text) || null,
            excerpt: clean(raw.excerpt) || null
          };
        }
      } catch (e) {
        warnings.push({ issue: 'fetch_failed', detail: 'Could not fetch ' + r.url });
      }
      out.push({ result: r, fetchedPage: fetchedPage });
    }
    return out;
  }

  /* ============================================================================
     4 — CLASSIFICATION
     Assign sourceRelationship / sourceType / allowedUses / disallowedUses /
     isOfficialLivePage / competitorRisk from the result + context.
  ============================================================================ */
  const STATS_ALLOWED = ['statistic', 'benchmark', 'industry_report', 'trend'];
  const COMMUNITY_ALLOWED = ['trend'];
  const COMMUNITY_DISALLOWED = ['statistic', 'benchmark', 'product_fact', 'industry_report'];

  const TRUSTED_TLD = /\.(gov|edu|ac\.[a-z]{2})\b/i;
  const REPORT_HINT = /(report|survey|benchmark|study|statistics|state of|index|whitepaper|research)/i;
  const RESEARCH_FIRM = /(gartner|forrester|mckinsey|statista|pew|nielsen|deloitte|hubspot|semrush|ahrefs|openview|amplitude|backlinko|content marketing institute|cmi)/i;
  const STATS_ROUNDUP = /(\d+\+?\s+(stats|statistics)|statistics (you|to know)|stats roundup|ultimate list of)/i;

  function classifySourceCandidate(result, ctx) {
    const ac = (ctx && ctx.articleContext) || {};
    const url = clean(result.url);
    const host = lc(domainOf(url));
    const title = clean(result.title);
    const snippet = clean(result.snippet);
    const hay = lc(title + ' ' + snippet + ' ' + url);
    const comparison = isComparisonArticle(ac);

    /* brand/product context for competitor detection */
    const ownDomains = collectOwnDomains(ctx);
    const isOwn = ownDomains.some((d) => host.indexOf(d) !== -1);

    /* ---- community ---- */
    if (/(^|\.)reddit\.com$/.test(host) || host === 'reddit.com') {
      return community('community_reddit');
    }
    if (/(^|\.)quora\.com$/.test(host) || host === 'quora.com') {
      return community('community_quora');
    }

    /* ---- official pricing page (own or, for comparison, any product) ---- */
    const looksPricing = /\/pricing(\/|$|\?)|pricing/i.test(url) || /\bpricing\b/.test(lc(title));
    const looksProduct = /\/(product|features|docs|documentation|product-docs)(\/|$|\?)/i.test(url);

    /* ---- competitor detection ---- */
    const competitor = detectCompetitor({ host, hay, isOwn, comparison });

    if (looksPricing && (isOwn || comparison)) {
      const base = {
        sourceRelationship: 'official_pricing_page',
        sourceType: 'pricing_page',
        allowedUses: ['product_fact'],
        disallowedUses: ['industry_report', 'statistic', 'benchmark', 'trend'],
        isOfficialLivePage: true,
        competitorRisk: isOwn ? 'none' : (competitor.risk === 'high' ? 'high' : 'medium')
      };
      return base;
    }
    if (looksProduct && (isOwn || comparison)) {
      return {
        sourceRelationship: 'official_product_page',
        sourceType: /docs|documentation/i.test(url) ? 'product_doc' : 'official_page',
        allowedUses: ['product_fact'],
        disallowedUses: ['industry_report', 'statistic', 'benchmark', 'trend'],
        isOfficialLivePage: true,
        competitorRisk: isOwn ? 'none' : (competitor.risk === 'high' ? 'high' : 'medium')
      };
    }

    /* ---- competitor (non-pricing/product) ---- */
    if (competitor.isCompetitor) {
      /* promotional case study / results / success story → high risk */
      const promotional = /(case study|success story|results|testimonial|customer story)/.test(hay);
      const risk = (competitor.risk === 'high' || promotional) ? 'high' : 'medium';
      return {
        sourceRelationship: 'competitor',
        sourceType: 'external_article',
        allowedUses: comparison && risk !== 'high' ? ['product_fact'] : [],
        disallowedUses: ['statistic', 'benchmark', 'industry_report', 'trend'],
        isOfficialLivePage: false,
        competitorRisk: risk
      };
    }

    /* ---- trusted external: gov/edu, research firm, or report-like ---- */
    const isReportLike = TRUSTED_TLD.test(host) || RESEARCH_FIRM.test(hay) || REPORT_HINT.test(hay);
    const isStatsRoundup = STATS_ROUNDUP.test(hay);

    if (isReportLike && !isStatsRoundup) {
      const type = /survey/i.test(hay) ? 'survey' : (REPORT_HINT.test(hay) ? 'industry_report' : 'external_article');
      return {
        sourceRelationship: 'trusted_external',
        sourceType: type,
        allowedUses: STATS_ALLOWED.slice(),
        disallowedUses: ['product_fact'],
        isOfficialLivePage: false,
        competitorRisk: 'none'
      };
    }

    /* ---- stats roundup / list post: cautious, cannot back hard stats ---- */
    if (isStatsRoundup) {
      return {
        sourceRelationship: 'trusted_external',
        sourceType: 'external_article',
        allowedUses: ['trend'],
        disallowedUses: ['statistic', 'benchmark', 'industry_report', 'product_fact'],
        isOfficialLivePage: false,
        competitorRisk: 'none',
        __statsRoundup: true
      };
    }

    /* ---- personal blog / niche expert / generic article ---- */
    return {
      sourceRelationship: 'trusted_external',
      sourceType: 'external_article',
      allowedUses: ['trend'],
      disallowedUses: ['statistic', 'benchmark', 'industry_report', 'product_fact'],
      isOfficialLivePage: false,
      competitorRisk: 'none'
    };

    function community(rel) {
      return {
        sourceRelationship: rel,
        sourceType: 'community_thread',
        allowedUses: COMMUNITY_ALLOWED.slice(),
        disallowedUses: COMMUNITY_DISALLOWED.slice(),
        isOfficialLivePage: false,
        competitorRisk: 'none'
      };
    }
  }

  /* domains the workspace owns (so we never flag ourselves as a competitor) */
  function collectOwnDomains(ctx) {
    const out = ['ranklyx.com', 'ranklyx'];
    const pages = (ctx && ctx.internalSources && ctx.internalSources.approvedImportedPages) || [];
    pages.forEach((p) => { const d = lc(domainOf(p.url || p.sourceUrl || '')); if (d) out.push(d); });
    return Array.from(new Set(out.filter(Boolean)));
  }

  /* heuristic competitor detection: a product/agency/service page that isn't ours.
     Conservative — only flags clear promotional/vendor pages, not editorial. */
  function detectCompetitor({ host, hay, isOwn, comparison }) {
    if (isOwn) return { isCompetitor: false, risk: 'none' };
    const vendorish = /(pricing|free trial|book a demo|sign up free|our platform|our software|why choose us|#1 .* (tool|software|platform))/i.test(hay);
    const promotional = /(case study|success story|customer results|testimonial|customer story)/i.test(hay);
    if (promotional && vendorish) return { isCompetitor: true, risk: 'high' };
    if (vendorish) return { isCompetitor: true, risk: comparison ? 'medium' : 'high' };
    return { isCompetitor: false, risk: 'none' };
  }

  /* ============================================================================
     5 — CLAIM EXTRACTION
     Short, factual, source-tied claim candidates. Never final note text, never
     invented. Uses fetched text when available, else snippet + title only.
  ============================================================================ */
  function extractClaimCandidates({ result, fetchedPage, classification, ctx }) {
    const text = clean(fetchedPage && fetchedPage.text) || clean(result.snippet);
    const title = clean(result.title);
    const claims = [];

    if (text) {
      /* prefer sentences that carry a number/percent for stat-capable sources */
      const sentences = text.replace(/\s+/g, ' ').split(/(?<=[.!?])\s+/).map(clean).filter(Boolean);
      const statCapable = (classification.allowedUses || []).some((u) => STATS_ALLOWED.indexOf(u) !== -1);
      const numeric = sentences.filter((s) => /\d/.test(s) && s.length <= 200);
      const pick = statCapable && numeric.length ? numeric : sentences;
      pick.slice(0, 3).forEach((s) => { if (s.length >= 20) claims.push(truncate(s, 200)); });
    }

    if (!claims.length && title) {
      claims.push(truncate(title, 160));
    }
    /* dedupe + cap */
    return Array.from(new Set(claims)).slice(0, 4);
  }

  function truncate(s, n) {
    s = clean(s);
    if (s.length <= n) return s;
    return s.slice(0, n - 1).replace(/\s+\S*$/, '') + '…';
  }

  /* ============================================================================
     6 — BUILD EXTERNAL CANDIDATES (end to end for the external side)
     queries → search → (optional) fetch → classify → claims → candidate shape.
  ============================================================================ */
  async function buildExternalSourceCandidates({ ctx, payload, searchProvider, fetchProvider, meta, warnings }) {
    warnings = warnings || [];
    meta = meta || {};
    if (typeof searchProvider !== 'function') {
      warnings.push({ issue: 'no_search_provider', detail: 'External research requested but no searchProvider is connected; using internal sources only.' });
      return [];
    }

    const plannedQueries = payload && payload.researchPlan && Array.isArray(payload.researchPlan.plannedQueries)
      ? payload.researchPlan.plannedQueries
      : [];
    const queries = plannedQueries.length
      ? plannedQueries.map((q) => clean(q.searchQuery)).filter(Boolean)
      : buildResearchSearchQueries({ ctx: ctx, payload: payload });

    let normalized = [];
    try {
      const raw = await searchProvider({
        queries: queries,
        plannedQueries: plannedQueries,
        maxResultsPerQuery: LIMITS.maxResultsPerQuery,
        searchPurpose: 'external_research_source_candidates',
        articleContext: (payload && payload.articleContext) || (ctx && ctx.articleContext) || null,
        metadata: { articleId: meta.articleId, workspaceId: meta.workspaceId, task: 'external_research_source_candidates' }
      });
      normalized = normalizeSearchResults(raw);
    } catch (e) {
      warnings.push({ issue: 'search_failed', detail: 'Web search failed; continuing with internal sources.' });
      return [];
    }

    if (!normalized.length) {
      warnings.push({ issue: 'no_search_results', detail: 'Web search returned no usable results.' });
      return [];
    }

    /* cap how many we bother to fetch/process */
    const capped = normalized.slice(0, LIMITS.maxQueries * LIMITS.maxResultsPerQuery);
    const detailed = await fetchSearchResultDetails({ results: capped, fetchProvider: fetchProvider, meta: meta, warnings: warnings });

    const candidates = [];
    detailed.forEach((d, i) => {
      const r = d.result, fp = d.fetchedPage;
      const cls = classifySourceCandidate(r, ctx);

      /* CONSERVATIVE snippet-only rule: if we couldn't fetch the page and the
         source isn't clearly official/report-based, strip stat-grade uses. */
      const snippetOnly = !fp || !fp.text;
      const officialOrReport = cls.isOfficialLivePage ||
        cls.sourceType === 'industry_report' || cls.sourceType === 'survey';
      let allowedUses = cls.allowedUses.slice();
      if (snippetOnly && !officialOrReport) {
        allowedUses = allowedUses.filter((u) => STATS_ALLOWED.indexOf(u) === -1);
        if (!allowedUses.length) allowedUses = ['trend'];
      }

      const date = (fp && (fp.updatedDate || fp.publishedDate)) ||
        r.updatedDate || r.publishedDate ||
        detectYear((fp && fp.title) || r.title) ||
        detectYear((fp && fp.text) || r.snippet);

      const excerpt = truncate(clean(fp && (fp.excerpt || fp.text)) || r.rawContent || r.snippet || r.title, LIMITS.excerptMaxChars);
      const claimCandidates = extractClaimCandidates({ result: r, fetchedPage: fp, classification: { allowedUses: allowedUses }, ctx: ctx });

      candidates.push({
        id: 'ext_' + (i + 1) + '_' + slug(domainOf(r.url)),
        sourcePublisher: clean((fp && fp.publisher) || r.publisher) || domainOf(r.url) || 'Unknown',
        sourceUrl: r.url,
        sourceTitle: clean((fp && fp.title) || r.title) || null,
        sourceDate: date || null,
        sourceRelationship: cls.sourceRelationship,
        sourceType: cls.sourceType,
        excerpt: excerpt,
        claimCandidates: claimCandidates,
        allowedUses: allowedUses,
        disallowedUses: cls.disallowedUses.slice(),
        isOfficialLivePage: !!cls.isOfficialLivePage,
        competitorRisk: cls.competitorRisk,
        /* internal-only processing hints (stripped before LLM) */
        __snippetOnly: snippetOnly,
        __statsRoundup: !!cls.__statsRoundup,
        __fetched: !snippetOnly
      });
    });

    return candidates;
  }

  function slug(s) {
    return lc(s).replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 24) || 'src';
  }

  /* ============================================================================
     7 — DEDUPE
     By normalized URL, and by publisher + similar title. Prefer originals over
     roundups, official over third-party, fetched over snippet-only, recent over
     old, low competitor risk over high.
  ============================================================================ */
  function normalizeUrlKey(url) {
    try {
      const u = new URL(url);
      const host = u.hostname.replace(/^www\./, '');
      let path = u.pathname.replace(/\/+$/, '');
      return (host + path).toLowerCase();
    } catch (e) {
      return lc(url).split('?')[0].replace(/\/+$/, '');
    }
  }
  function titleKey(c) {
    return lc(c.sourcePublisher) + '::' + lc(c.sourceTitle).replace(/[^a-z0-9]+/g, ' ').trim().slice(0, 60);
  }
  function candidateScore(c) {
    let s = 0;
    if (c.isOfficialLivePage) s += 5;
    if (c.sourceType === 'industry_report' || c.sourceType === 'survey') s += 4;
    if (c.__fetched) s += 3;
    if (c.__statsRoundup) s -= 4;
    if (c.sourceRelationship === 'approved_internal' || c.sourceRelationship === 'approved_case_study_library') s += 4;
    if (c.competitorRisk === 'high') s -= 6;
    else if (c.competitorRisk === 'medium') s -= 2;
    const yr = c.sourceDate ? parseInt(String(c.sourceDate).slice(0, 4), 10) : 0;
    if (yr) s += Math.max(0, yr - 2018) * 0.5;
    if ((c.claimCandidates || []).length) s += 1;
    return s;
  }

  function dedupeSourceCandidates(candidates) {
    const byUrl = new Map();
    (candidates || []).forEach((c) => {
      if (!c) return;
      const key = c.sourceUrl ? normalizeUrlKey(c.sourceUrl) : (c.id || titleKey(c));
      const prev = byUrl.get(key);
      if (!prev || candidateScore(c) > candidateScore(prev)) byUrl.set(key, c);
    });
    /* second pass: collapse publisher+title near-dupes */
    const byTitle = new Map();
    Array.from(byUrl.values()).forEach((c) => {
      const tk = titleKey(c);
      if (!clean(c.sourceTitle)) { byTitle.set(c.id || c.sourceUrl, c); return; }
      const prev = byTitle.get(tk);
      if (!prev || candidateScore(c) > candidateScore(prev)) byTitle.set(tk, c);
    });
    return Array.from(byTitle.values());
  }

  /* ============================================================================
     8 — MERGE internal + external, apply category caps, strip internal fields.
  ============================================================================ */
  function mergeSourceCandidates(internalCandidates, externalCandidates, opts) {
    opts = opts || {};
    const comparison = !!opts.comparisonArticle;

    const internal = (internalCandidates || []).slice(0, LIMITS.maxInternal);
    let external = dedupeSourceCandidates(externalCandidates || []);

    /* drop high-risk competitor candidates by default (never passed to the LLM) */
    external = external.filter((c) => c.competitorRisk !== 'high');
    /* competitor candidates only survive for comparison-style articles */
    external = external.filter((c) => c.sourceRelationship !== 'competitor' || comparison);

    /* category caps */
    const community = [];
    const competitor = [];
    const otherExternal = [];
    external.sort((a, b) => candidateScore(b) - candidateScore(a));
    external.forEach((c) => {
      if (c.sourceRelationship === 'community_reddit' || c.sourceRelationship === 'community_quora') {
        if (community.length < LIMITS.maxCommunity) community.push(c);
      } else if (c.sourceRelationship === 'competitor') {
        if (competitor.length < LIMITS.maxCompetitor) competitor.push(c);
      } else {
        if (otherExternal.length < LIMITS.maxExternalNonCommunity) otherExternal.push(c);
      }
    });

    const merged = internal.concat(otherExternal, community, competitor).slice(0, LIMITS.maxTotalCandidates);
    /* strip internal-only processing fields before handing to the LLM */
    return merged.map(stripInternalFields);
  }

  function stripInternalFields(c) {
    const out = {};
    ['id', 'sourcePublisher', 'sourceUrl', 'sourceTitle', 'sourceDate', 'sourceRelationship',
     'sourceType', 'excerpt', 'claimCandidates', 'allowedUses', 'disallowedUses',
     'isOfficialLivePage', 'competitorRisk'].forEach((k) => { out[k] = c[k]; });
    return out;
  }

  /* ============================================================================
     9 — ADAPTER: produce merged sourceCandidates for the workflow.
     Returns { sourceCandidates, warnings, stats }. Never throws.
  ============================================================================ */
  function createExternalResearchSourceAdapter(options) {
    options = options || {};
    const searchProvider = options.searchProvider;
    const fetchProvider = options.fetchProvider;

    return async function getSourceCandidates({ ctx, payload, meta }) {
      const warnings = [];
      meta = meta || {};
      const ac = (payload && payload.articleContext) || (ctx && ctx.articleContext) || {};
      const comparison = isComparisonArticle(ac);

      /* internal candidates always come from the foundation */
      const internal = (RA.buildSourceCandidatesForResearchLLM ? RA.buildSourceCandidatesForResearchLLM(ctx) : []) || [];

      let external = [];
      try {
        external = await buildExternalSourceCandidates({
          ctx: ctx, payload: payload,
          searchProvider: searchProvider, fetchProvider: fetchProvider,
          meta: meta, warnings: warnings
        });
      } catch (e) {
        warnings.push({ issue: 'external_research_failed', detail: 'External source retrieval failed; using internal sources only.' });
        external = [];
      }

      const sourceCandidates = mergeSourceCandidates(internal, external, { comparisonArticle: comparison });
      return {
        sourceCandidates: sourceCandidates,
        warnings: warnings,
        stats: {
          internalCount: internal.length,
          externalRawCount: external.length,
          mergedCount: sourceCandidates.length
        }
      };
    };
  }

  /* ============================================================================
     DEV/TEST MOCKS — never run unless explicitly passed into the workflow.
  ============================================================================ */
  function createMockExternalSourceResults() {
    return { results: [
      { query: 'saas onboarding statistics report', title: 'SaaS Onboarding Statistics 2025', url: 'https://www.shno.co/marketing-statistics/saas-onboarding-statistics', snippet: 'Activation rates averaged 37.5% in 2025, with 43% of SMB losses in the first 90 days.', publisher: 'Shno', publishedDate: '2025-02-10' },
      { query: 'saas onboarding industry report', title: 'State of Product Onboarding 2025 (Survey)', url: 'https://userorbit.com/blog/2025-onboarding-report', snippet: '82% of users expect onboarding tailored to their role, per a survey of 500 SaaS users.', publisher: 'Userorbit', publishedDate: '2025-01-05' },
      { query: 'saas onboarding pain points Reddit', title: 'Why do users churn during onboarding?', url: 'https://www.reddit.com/r/SaaS/comments/abc/onboarding', snippet: 'Many users say confusing setup and unclear value are the top reasons they abandon a product.', publisher: 'reddit.com', publishedDate: '2025-03-01' },
      { query: 'saas onboarding examples', title: '7 stats every PM should know', url: 'https://exampleblog.com/77-onboarding-stats-you-must-know', snippet: 'A roundup of 77 onboarding statistics from around the web.', publisher: 'exampleblog.com', publishedDate: '2024-11-01' },
      { query: 'competitor pricing', title: 'CompetitorTool Pricing — Free trial, book a demo', url: 'https://competitortool.com/pricing', snippet: 'See our plans. Why choose us: the #1 onboarding software. Read our customer success story.', publisher: 'competitortool.com', publishedDate: null }
    ] };
  }
  function createMockFetchedPages() {
    return {
      'https://www.shno.co/marketing-statistics/saas-onboarding-statistics': {
        url: 'https://www.shno.co/marketing-statistics/saas-onboarding-statistics',
        title: 'SaaS Onboarding Statistics 2025', publisher: 'Shno', publishedDate: '2025-02-10', updatedDate: '2025-04-01',
        text: 'The average activation rate for SaaS products was 37.5% in 2025. 43% of SMB SaaS customer losses occur within the first 90 days after purchase.',
        excerpt: 'Activation averaged 37.5% in 2025; 43% of SMB losses occur in the first 90 days.'
      }
    };
  }
  function createMockSearchProvider() {
    const canned = createMockExternalSourceResults();
    return async function searchProvider(req) {
      /* echo queries onto results so normalize keeps them */
      return { results: canned.results.map((r) => Object.assign({}, r)) };
    };
  }
  function createMockFetchProvider() {
    const pages = createMockFetchedPages();
    return async function fetchProvider(req) {
      return pages[req.url] || null;
    };
  }

  /* ---------- exports ---------- */
  Object.assign(RA, {
    RESEARCH_SOURCE_CANDIDATE_VERSION,
    SOURCE_RETRIEVAL_LIMITS: LIMITS,
    buildResearchSearchQueries,
    normalizeSearchResults,
    fetchSearchResultDetails,
    classifySourceCandidate,
    extractClaimCandidates,
    buildExternalSourceCandidates,
    mergeSourceCandidates,
    dedupeSourceCandidates,
    createExternalResearchSourceAdapter,
    /* dev mocks */
    createMockSearchProvider,
    createMockFetchProvider,
    createMockExternalSourceResults,
    createMockFetchedPages
  });
  Object.assign(RN, {
    createExternalResearchSourceAdapter,
    buildResearchSearchQueries,
    mergeSourceCandidates,
    dedupeSourceCandidates,
    createMockSearchProvider,
    createMockFetchProvider
  });
})();
