/* Rank Lyx — AI Research Agent / REAL Research LLM prompt + adapter (v1)
   ------------------------------------------------------------------------------
   The production stand-in for the Research LLM. This module owns:
     • the provider-neutral SYSTEM + USER prompts (the actual research rules)
     • a provider-neutral ADAPTER built from a callLLM() function
     • a safe JSON PARSER for the model's response
     • buildSourceCandidatesForResearchLLM() — turns the foundation's internal
       sources into the source-candidate contract the LLM must cite from

   What this module is NOT:
     • It is NOT external web research. No fetch, no search API, no browsing.
     • It does NOT hardcode any provider (OpenAI/Claude/Gemini) and adds no keys.
     • It does NOT validate business rules or save anything — the workflow runs
       validateResearchResponse + repairResearchResponseOnce, then saves.
     • It does NOT reintroduce foundation-level recommendations. The LLM decides
       what each section needs; the foundation/payload stays neutral.

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

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

  const RESEARCH_LLM_PROMPT_VERSION = 1;

  /* small local mirrors of the contract vocab (kept in sync with the validator) */
  const NOTE_TYPES = (RA.ALLOWED_RESEARCH_NOTE_TYPES || [
    'product_fact', 'statistic', 'benchmark', 'industry_report', 'trend'
  ]);

  /* ============================================================================
     SOURCE CANDIDATES — what the LLM is ALLOWED to cite.
     Built from the foundation's internal sources only (no web research yet).
     Each candidate follows the source-candidate contract; the LLM must not cite
     anything outside this list and must not invent URLs/publishers/titles.
  ============================================================================ */
  function buildSourceCandidatesForResearchLLM(ctx) {
    const internal = (ctx && ctx.internalSources) || {};
    const out = [];
    let n = 0;
    const cid = (prefix) => prefix + '_' + (++n);

    /* Brand knowledge → product facts + pricing facts (approved internal). */
    const bk = internal.brandKnowledge || null;
    if (bk) {
      if (bk.businessDescription) {
        out.push({
          id: cid('brand'),
          sourcePublisher: 'Workspace Brand Knowledge',
          sourceUrl: null, sourceTitle: null, sourceDate: null,
          sourceRelationship: 'approved_internal',
          sourceType: 'brand_knowledge',
          excerpt: bk.businessDescription,
          claimCandidates: [bk.positioningNotes].filter(Boolean),
          allowedUses: ['product_fact'],
          disallowedUses: ['statistic', 'benchmark', 'industry_report', 'trend'],
          isOfficialLivePage: false,
          competitorRisk: 'none'
        });
      }
      (bk.features || []).forEach((f) => out.push({
        id: cid('feature'),
        sourcePublisher: 'Workspace Brand Knowledge',
        sourceUrl: null, sourceTitle: null, sourceDate: null,
        sourceRelationship: 'approved_internal',
        sourceType: 'product_doc',
        excerpt: f,
        claimCandidates: [f],
        allowedUses: ['product_fact'],
        disallowedUses: ['statistic', 'benchmark', 'industry_report', 'trend'],
        isOfficialLivePage: false,
        competitorRisk: 'none'
      }));
      (bk.pricing || []).forEach((p) => out.push({
        id: cid('pricing'),
        sourcePublisher: 'Workspace Brand Knowledge',
        sourceUrl: null, sourceTitle: null, sourceDate: null,
        sourceRelationship: 'approved_internal',
        sourceType: 'pricing_page',
        excerpt: (p.plan ? p.plan + ' — ' : '') + (p.price || '') + (p.detail ? ' (' + p.detail + ')' : ''),
        claimCandidates: [(p.plan || 'Plan') + ': ' + (p.price || '') + (p.detail ? ', ' + p.detail : '')],
        allowedUses: ['product_fact'],
        disallowedUses: ['statistic', 'benchmark', 'industry_report', 'trend'],
        isOfficialLivePage: false,
        competitorRisk: 'none'
      }));
    }

    /* Approved case study library → case study candidates only. */
    (internal.approvedCaseStudyLibrary || []).forEach((c) => out.push({
      id: c.id || cid('casestudy'),
      sourcePublisher: 'Rank Lyx',
      sourceUrl: c.sourceUrl || c.url || null,
      sourceTitle: c.title || null,
      sourceDate: c.date || null,
      sourceRelationship: 'approved_case_study_library',
      sourceType: 'case_study',
      excerpt: (c.title || '') + (c.metric ? ' — ' + c.metric : ''),
      claimCandidates: [c.metric, c.title].filter(Boolean),
      allowedUses: [],
      disallowedUses: ['product_fact', 'statistic', 'benchmark', 'industry_report', 'trend'],
      isOfficialLivePage: false,
      competitorRisk: 'none'
    }));

    /* Approved testimonials → example (real_world) candidates. */
    (internal.approvedTestimonials || []).forEach((t) => out.push({
      id: t.id || cid('testimonial'),
      sourcePublisher: t.author || 'Customer testimonial',
      sourceUrl: t.sourceUrl || null,
      sourceTitle: null,
      sourceDate: t.date || null,
      sourceRelationship: 'approved_internal',
      sourceType: 'testimonial',
      excerpt: t.quote || '',
      claimCandidates: [t.quote].filter(Boolean),
      allowedUses: ['product_fact'],
      disallowedUses: ['statistic', 'benchmark', 'industry_report', 'trend'],
      isOfficialLivePage: false,
      competitorRisk: 'none'
    }));

    /* Approved customer stories → example candidates. */
    (internal.approvedCustomerStories || []).forEach((s) => out.push({
      id: s.id || cid('story'),
      sourcePublisher: 'Rank Lyx',
      sourceUrl: s.sourceUrl || null,
      sourceTitle: s.title || null,
      sourceDate: s.date || null,
      sourceRelationship: 'approved_internal',
      sourceType: 'customer_story',
      excerpt: s.story || s.title || '',
      claimCandidates: [s.story].filter(Boolean),
      allowedUses: ['product_fact'],
      disallowedUses: ['statistic', 'benchmark', 'industry_report', 'trend'],
      isOfficialLivePage: false,
      competitorRisk: 'none'
    }));

    /* Approved imported pages → official live page candidates. */
    (internal.approvedImportedPages || []).forEach((pg) => out.push({
      id: pg.id || cid('page'),
      sourcePublisher: pg.publisher || 'Rank Lyx',
      sourceUrl: pg.url || pg.sourceUrl || null,
      sourceTitle: pg.title || null,
      sourceDate: pg.date || null,
      sourceRelationship: pg.isPricing ? 'official_pricing_page' : 'official_product_page',
      sourceType: pg.isPricing ? 'pricing_page' : 'official_page',
      excerpt: pg.excerpt || pg.title || '',
      claimCandidates: pg.claimCandidates || [],
      allowedUses: ['product_fact'],
      disallowedUses: ['statistic', 'benchmark', 'industry_report', 'trend'],
      isOfficialLivePage: true,
      competitorRisk: 'none'
    }));

    return out;
  }

  /* ============================================================================
     SYSTEM PROMPT — the durable research rules. Provider-neutral, no payload data.
  ============================================================================ */
  function buildResearchLLMSystemPrompt() {
    return [
'You are the Research LLM inside an AI writing software. You do not write the article. You do not rewrite the outline. You do not create final copy. You create short, useful research notes for selected eligible sections.',
'',
'CORE MISSION',
'Read the article context, outline, eligible sections, protected notes, internal sources, source candidates, and rules. Select the best eligible sections for research support. Create one strong research note for each selected section. Return only valid JSON.',
'',
'OUTPUT SHAPE (return EXACTLY this object):',
'{ "notes": [], "coverageStatus": "within_target" | "below_target", "reason": string | null }',
'',
'Each note must follow this shape:',
'{',
'  "id": string,',
'  "articleId": string, "sectionId": string, "headingId": string, "headingTitle": string,',
'  "headingLevel": "intro" | 2 | 3,',
'  "noteType": "product_fact" | "statistic" | "benchmark" | "industry_report" | "trend",',
'  "note": string, "whyItMatters": string,',
'  "sourcePublisher": string | null, "sourceUrl": string | null, "sourceTitle": string | null,',
'  "isTimeSensitive": boolean, "sourceDate": string | null,',
'  "exampleKind": null,',
'  "sourceRelationship": "approved_internal" | "approved_case_study_library" | "trusted_external" | "official_product_page" | "official_pricing_page" | "community_reddit" | "community_quora" | "non_competing_brand" | "competitor" | "unknown",',
'  "competitorRisk": "none" | "low" | "medium" | "high",',
'  "origin": "ai", "editedByUser": false,',
'  "createdAt": string, "updatedAt": null, "deletedAt": null',
'}',
'',
'ALLOWED NOTE TYPES (use ONLY these five):',
'product_fact, statistic, benchmark, industry_report, trend.',
'NEVER use: Example, Definition, Case study, Pricing fact, Comparison point, Quote, Expert insight, Data point, Study, Research report, Brand internal opinion, Brand feature, Brand pricing, Competitor pricing, Competitor features, or any other label.',
'',
'ARTICLE CONTEXT RULES',
'Only topic/title and primary keyword are guaranteed. Post type, additional information, and selected ICP context may be empty. Goal, secondary keywords, tone of voice, unselected ICPs, and Brand Voice are not research inputs. If optional fields are empty, infer likely context from the topic, primary keyword, post type (if any), outline headings, talking points, brand knowledge, selected ICP context, and source candidates. Do not complain that fields are missing. Do not invent those fields in the output - use them only for reasoning.',
'',
'SECTION SELECTION RULES',
'Use ONLY headingIds present in eligibleSections. Never create notes for sections outside eligibleSections. Never create notes for H4, H5, or H6. Never create notes for a conclusion, final recap, FAQ parent heading, grouping/navigational heading, or a parent H2 that only introduces child H3s (these are already excluded from eligibleSections — do not re-add them).',
'',
'COVERAGE RULES',
'Support roughly one third of eligible sections when strong notes are available. minNotes = floor(eligibleSections.length / 3). maxNotes = ceil(eligibleSections.length / 3). Create no more than maxNotes. Try to create at least minNotes.',
'QUALITY ESCAPE HATCH: If there are not enough strong, source-backed notes, return fewer than minNotes. Then coverageStatus MUST be "below_target" and reason MUST clearly explain why (weak sources, missing sources, outdated sources, competitor risk, irrelevant material, or no approved case studies). NEVER create weak research just to hit the minimum.',
'',
'ONE NOTE PER SECTION',
'Each selected section receives exactly one note. Never output two notes for the same headingId. If a section could use multiple note types, choose the single strongest one.',
'',
'PROTECTED NOTE RULES',
'Never create a note for any headingId listed in protectedNotes (manual notes, or AI notes edited by the user). If a protected section would otherwise fit, skip it and pick another eligible section when possible.',
'',
'NOTE TYPE SELECTION (guidelines, not commands - use judgment):',
'Use statistic for sourced numbers, benchmark for sourced comparative performance standards, industry_report for sourced report findings, trend for sourced market/user-signal trends, and product_fact for sourced product, feature, plan, integration, or capability facts. Do not create definitions, examples, comparison advice, summaries, writing instructions, or generic explanations as research notes.',
'',
'SOURCE RULES (critical)',
'Use ONLY sourceCandidates supplied in the payload. Do not invent sources, URLs, publishers, or source titles. Do not cite any publisher, report, article, Reddit thread, Quora answer, product page, or pricing page unless it appears in sourceCandidates. The source must fit the claim: statistics need credible statistical sources; benchmarks need benchmark sources; industry_report notes need report/survey sources; product_fact notes need official product pages, docs, or approved internal sources; trend notes need recent market, report, or user-signal sources. If no appropriate source exists, skip the section.',
'NO-SOURCE RULE',
'Do not create no-source AI research notes. If a selected section has no directly matching sourceCandidate, skip it and explain the shortfall in coverageStatus/reason.',
'',
'INTERNAL SOURCE RULES',
'Approved internal sources may include brand knowledge, product/pricing information, approved case studies, approved testimonials, approved customer stories, and imported pages/docs. Use them only when they genuinely help the section; never force an internal source into an unrelated section.',
'Never use sourceRelationship "approved_internal" for third-party products, competitor products, generic market facts, or claims that are not directly anchored to a supplied internal sourceCandidate. For example, do not label facts about Zendesk, Intercom, Freshdesk, or other external tools as approved_internal unless those exact facts appear in sourceCandidates.',
'If the available sourceCandidates do not directly support this article topic, return fewer notes or zero notes with coverageStatus "below_target"; do not disguise unsupported claims as internal research.',
'',
'DISALLOWED NOTE CONTENT',
'Do not create examples, case studies, definitions, section summaries, comparison talking points, pricing_fact notes, generic explanations, article copy, or writing instructions. Research notes are evidence only.',
'',
'EXAMPLE AND DEFINITION RULES',
'Never output hypothetical examples, real-world examples, definitions, or explanatory notes. If a section only needs an explanation, it does not need research.',
'',
'REDDIT AND QUORA RULES',
'Community relationships are community_reddit and community_quora. They may only support trend notes framed as user signals: pain points, objections, common frustrations, user language, and real questions. Never use Reddit or Quora for statistics, benchmarks, product facts, industry reports, numerical proof, or market-wide claims.',
'',
'TIME-SENSITIVE SOURCE RULES',
'Set isTimeSensitive true when freshness affects trust. statistic, benchmark, industry_report, and trend always require a sourceDate unless using an official live product/pricing/doc page. Time-sensitive product_fact notes also require a sourceDate unless using an official live page. Sources must be within the last 24 months from today; if no recent date is available, skip the note.',
'',
'COMPETITOR RULES',
'Never output competitorRisk "high". competitorRisk "medium" is allowed only when the post type requires competitor discussion (Product Comparison, Product Roundup, Alternatives, Pricing Comparison, Best Tools, Best Software). Competitor sources may only support neutral facts when the article type requires them (pricing, features, plan limits, integrations, product categories, public positioning). Never use competitor sources for success stories, case studies, glowing examples, customer results, service-process inspiration, or anything that makes a competitor look like the authority.',
'',
'SOURCE FIELD RULES',
'sourcePublisher = the visible source name. sourceUrl = the exact URL from the sourceCandidate. sourceTitle = the exact title from the sourceCandidate when available. Do not put the source title inside the note text and do not add citations inside the note body — use the source fields.',
'',
'NOTE WRITING STYLE',
'The note field must be 1 to 3 sentences, at most 20 words per sentence, at most 60 words total, clear, specific, and directly useful to the future Writing Agent. No paragraph dumps, no final article copy, no long explanations, no over-explaining the source.',
'',
'whyItMatters STYLE',
'whyItMatters must be 1 to 2 short sentences explaining how the Writing Agent should use the note, specific to the section, never generic. Do not write lines like "This is useful for the article", "This helps improve credibility", "This gives more context", or "This makes the article better".',
'',
'OUTPUT RULES',
'Return valid JSON only. No markdown, no explanation outside the JSON, no comments, no trailing text, and do not wrap the JSON in code fences.'
    ].join('\n');
  }

  /* ============================================================================
     USER PROMPT — the per-run payload + reminders. Compact but complete.
  ============================================================================ */
  /* Build the [AI CONTEXT] block for the Research prompt from the shared AI
     Context Engine, using the COMPACT "research" profile (Product Knowledge
     plus selected ICP context, with Brand Voice excluded). Fully defensive: any
     failure returns an empty block so the Research article button never breaks.
     Emits SAFE [ResearchContext] diagnostics only — never formattedContext,
     outline, brief, or any private Knowledge content. Returns { text, meta }. */
  function buildResearchAIContextBlock(payload) {
    try { console.log('[ResearchContext] researchContextStarted'); } catch (e) {}
    var providedContext = payload && payload.knowledgeContext && typeof payload.knowledgeContext === 'object'
      ? payload.knowledgeContext
      : null;
    var hasEngine = (typeof window !== 'undefined' && typeof window.buildAIContext === 'function');
    try { console.log('[ResearchContext] hasAIContextEngine', hasEngine); } catch (e) {}
    var aiContext = providedContext;
    if (!aiContext) {
      if (!hasEngine) {
        try { console.log('[ResearchContext] researchContextSkipped', { reason: 'engine-unavailable' }); } catch (e) {}
        return { text: '', meta: { injected: false, hasEngine: false } };
      }
      try {
        var ac = payload && payload.articleContext ? payload.articleContext : {};
        aiContext = window.buildAIContext({
          taskType: 'research',
          selectedIcpId: ac.selectedIcpId || null,
          selectedIcpOnly: true,
          resolvedIcp: ac.selectedIcp || null,
          includeBrandVoice: false
        });
      } catch (error) {
        try { console.warn('[ResearchContext] researchContextFailed', { message: (error && error.message) ? error.message : String(error) }); } catch (e) {}
        return { text: '', meta: { injected: false, hasEngine: true, failed: true } };
      }
    }
    var formatted = (aiContext && typeof aiContext.formattedContext === 'string') ? aiContext.formattedContext : '';
    var diag = (aiContext && aiContext.diagnostics) ? aiContext.diagnostics : {};
    if (providedContext && diag.knowledgeSource !== 'article_snapshot') {
      throw new Error('Invalid Article Knowledge context.');
    }
    try {
      console.log('[ResearchContext] taskType', diag.taskType || 'research');
      console.log('[ResearchContext] contextChars', formatted.length);
      console.log('[ResearchContext] blocksIncluded', diag.blocksIncluded || []);
      console.log('[ResearchContext] missingKnowledge', diag.missingKnowledge || []);
      console.log('[ResearchContext] selectedIcpResolution', diag.selectedIcpResolution || null);
    } catch (e) {}

    if (!formatted.trim()) {
      if (providedContext) throw new Error('Saved Article Knowledge is empty.');
      try { console.log('[ResearchContext] researchContextSkipped', { reason: 'empty-context' }); } catch (e) {}
      return { text: '', meta: { injected: false, hasEngine: true, contextChars: 0, blocksIncluded: diag.blocksIncluded || [], missingKnowledge: diag.missingKnowledge || [] } };
    }

    var C = [];
    C.push('[AI CONTEXT]');
    C.push('Saved Knowledge describing the brand, product, selected audience, and research-relevant context.');
    C.push('Use it to choose more relevant research angles. It is INTERNAL context, not');
    C.push('external research and not a citable source.');
    C.push('');
    C.push(formatted);
    C.push('');
    C.push('HOW TO USE THE AI CONTEXT (research instruction hierarchy):');
    C.push('1. The current article brief and outline below control the research task.');
    C.push('2. Use Knowledge context to choose more relevant research angles, not to replace external research.');
    C.push('3. Product Knowledge can guide which use cases, features, or pain points matter.');
    C.push('4. ICP Knowledge can guide which risks, objections, and decision criteria matter.');
    C.push('5. Brand Voice is excluded from Research and must not influence source selection, searches, or factual claims.');
    C.push('6. Do not invent facts from Knowledge.');
    C.push('7. Do not treat saved Product Knowledge as external research.');
    C.push('8. Do NOT cite Brand Profile, Product Knowledge, or ICP Knowledge as external sources. Use ONLY sources from sourceCandidates for external claims.');
    C.push('9. If a note relies on internal context, it must be clearly labeled as internal context, following the existing internal-source rules - never disguised as an external citation.');
    C.push('10. Do not force brand or product mentions into notes, and do not turn notes into promotional copy.');
    C.push('');

    try { console.log('[ResearchContext] researchContextInjected', { contextChars: formatted.length }); } catch (e) {}
    return {
      text: C.join('\n'),
      meta: { injected: true, hasEngine: hasEngine, contextChars: formatted.length, blocksIncluded: diag.blocksIncluded || [], missingKnowledge: diag.missingKnowledge || [], selectedIcpResolution: diag.selectedIcpResolution || null }
    };
  }
  function buildResearchLLMUserPrompt(payload) {
    payload = payload || {};
    const ac = payload.articleContext || {};
    const oc = payload.outline || {};
    const rules = payload.rules || {};
    const eligible = oc.eligibleSections || [];
    const budget = RA.coverageBudget ? RA.coverageBudget(eligible.length) : {
      minNotes: eligible.length ? Math.max(1, Math.floor(eligible.length / 3)) : 0,
      maxNotes: eligible.length ? Math.max(1, Math.ceil(eligible.length / 3)) : 0
    };
    const minNotes = budget.minNotes;
    const maxNotes = budget.maxNotes;
    const createdAt = new Date().toISOString();

    /* trim eligible sections to just what the LLM needs to choose + attach */
    const eligibleForLLM = eligible.map((s) => ({
      headingId: s.headingId,
      sectionId: s.sectionId,
      headingTitle: s.headingTitle,
      headingLevel: s.headingLevel,
      parentHeadingTitle: s.parentHeadingTitle || null,
      isIntro: !!s.isIntro,
      talkingPoints: s.talkingPoints || []
    }));

    const internalSummary = summarizeInternalSources(payload.internalSources);
    const sourceCandidates = payload.sourceCandidates || [];

    const obj = {
      articleContext: {
        topic: ac.topic || null,
        primaryKeyword: ac.primaryKeyword || null,
        postType: ac.postType || null,
        searchIntent: ac.searchIntent || null,
        selectedIcpId: ac.selectedIcpId || null,
        selectedIcpName: ac.selectedIcpName || null,
        selectedIcpResolution: ac.selectedIcpResolution || 'none_selected',
        selectedIcp: ac.selectedIcp ? {
          id: ac.selectedIcp.id || ac.selectedIcpId || null,
          name: ac.selectedIcp.name || ac.selectedIcpName || null,
          text: ac.selectedIcp.text || ''
        } : null,
        additionalInformation: ac.additionalInformation || null
      },
      coverage: {
        eligibleSectionCount: eligible.length,
        minNotes: minNotes,
        maxNotes: maxNotes
      },
      eligibleSections: eligibleForLLM,
      protectedNotes: payload.protectedNotes || [],
      internalSourcesSummary: internalSummary,
      sourceCandidates: sourceCandidates,
      rules: {
        coverage: rules.coverage || { minRatio: 0.33, maxRatio: 0.34, oneNotePerSection: true },
        allowedNoteTypes: rules.allowedNoteTypes || NOTE_TYPES
      },
      outputContract: {
        shape: '{ "notes": [], "coverageStatus": "within_target" | "below_target", "reason": string | null }',
        origin: 'ai',
        editedByUser: false,
        createdAt: createdAt,
        updatedAt: null,
        deletedAt: null
      }
    };

    var aiContextBlock = buildResearchAIContextBlock(payload);
    var baseLines = [
'Create research notes for this article. Use the data below.',
'',
'INPUT (JSON):',
JSON.stringify(obj, null, 2),
'',
'REMINDERS:',
'- Attach notes ONLY to headingIds in eligibleSections; never to a protectedNotes headingId.',
'- Aim for ' + minNotes + ' to ' + maxNotes + ' notes; one note per section maximum.',
'- Use ONLY sources from sourceCandidates. Never invent a source, URL, publisher, or title.',
'- If no sourceCandidate supports a section, skip it. Do not create hypothetical examples, definitions, or generic explanation notes.',
'- If there are not enough strong, well-sourced notes, return fewer and set coverageStatus to "below_target" with a specific reason.',
'- Use "createdAt": "' + createdAt + '" for every note; set updatedAt and deletedAt to null; origin "ai"; editedByUser false.',
'- Return valid JSON only — no markdown, no code fences, no commentary.'
    ];
    return (aiContextBlock.text ? (aiContextBlock.text + '\n') : '') + baseLines.join('\n');
  }

  function summarizeInternalSources(internal) {
    internal = internal || {};
    const bk = internal.brandKnowledge || null;
    return {
      hasBrandKnowledge: !!bk,
      businessDescription: bk ? (bk.businessDescription || null) : null,
      approvedCaseStudyCount: (internal.approvedCaseStudyLibrary || []).length,
      approvedTestimonialCount: (internal.approvedTestimonials || []).length,
      approvedCustomerStoryCount: (internal.approvedCustomerStories || []).length,
      approvedImportedPageCount: (internal.approvedImportedPages || []).length
    };
  }

  /* Convenience: both messages at once, with sourceCandidates injected into the
     payload if the caller hasn't already added them. */
  function buildResearchLLMMessages(payload, ctx) {
    const enriched = Object.assign({}, payload || {});
    if (!enriched.sourceCandidates) {
      enriched.sourceCandidates = buildSourceCandidatesForResearchLLM(ctx || payloadCtxFallback(enriched));
    }
    return {
      systemPrompt: buildResearchLLMSystemPrompt(),
      userPrompt: buildResearchLLMUserPrompt(enriched),
      payload: enriched
    };
  }

  /* The payload doesn't carry internalSources by default (the foundation puts
     them on the context). Fall back to a minimal shape so candidate-building
     never throws when only a payload is passed. */
  function payloadCtxFallback(payload) {
    return { internalSources: (payload && payload.internalSources) || {} };
  }

  /* ============================================================================
     PARSER — safe JSON parsing only (no business validation).
  ============================================================================ */
  function parseResearchLLMResponse(raw) {
    /* already an object */
    if (raw && typeof raw === 'object') {
      return normalizeShape(raw);
    }
    if (typeof raw !== 'string') {
      return parseError('The research model returned no parseable content.');
    }

    let text = raw.trim();
    /* tolerate accidental code fences even though the prompt forbids them */
    const fence = text.match(/```(?:json)?\s*([\s\S]*?)```/i);
    if (fence) text = fence[1].trim();
    /* fall back to the first {...} block if there's stray prose */
    if (text[0] !== '{') {
      const brace = text.indexOf('{');
      const last = text.lastIndexOf('}');
      if (brace !== -1 && last > brace) text = text.slice(brace, last + 1);
    }

    try {
      return normalizeShape(JSON.parse(text));
    } catch (e) {
      return parseError('The research model returned invalid JSON.');
    }
  }

  function normalizeShape(obj) {
    const notes = Array.isArray(obj.notes) ? obj.notes : [];
    let coverageStatus = obj.coverageStatus;
    if (coverageStatus !== 'within_target' && coverageStatus !== 'below_target') {
      coverageStatus = notes.length ? 'within_target' : 'below_target';
    }
    const reason = (obj.reason == null || obj.reason === '') ? null : String(obj.reason);
    return { notes: notes, coverageStatus: coverageStatus, reason: reason };
  }

  function parseError(message) {
    return { notes: [], coverageStatus: 'below_target', reason: message, parseError: true };
  }

  const PLAN_NEEDS = ['statistic', 'benchmark', 'industry_report', 'trend', 'product_fact'];
  const PLAN_NEED_ALIASES = {
    stat: 'statistic',
    statistics: 'statistic',
    benchmark: 'benchmark',
    report: 'industry_report',
    industry_report: 'industry_report',
    product: 'product_fact',
    pricing: 'product_fact'
  };

  function normalizePlanNeed(value) {
    const raw = String(value || '').trim().toLowerCase().replace(/[\s-]+/g, '_');
    return PLAN_NEEDS.indexOf(raw) !== -1 ? raw : (PLAN_NEED_ALIASES[raw] || null);
  }

  function planBudgets(payload) {
    const eligible = payload && payload.outline && Array.isArray(payload.outline.eligibleSections)
      ? payload.outline.eligibleSections
      : [];
    const budget = RA.coverageBudget ? RA.coverageBudget(eligible.length) : {
      minNotes: eligible.length ? Math.max(1, Math.floor(eligible.length / 3)) : 0,
      maxNotes: eligible.length ? Math.max(1, Math.ceil(eligible.length / 3)) : 0
    };
    return {
      eligibleCount: eligible.length,
      minQueries: budget.minNotes,
      maxQueries: Math.min(12, budget.maxNotes)
    };
  }

  function buildResearchPlanSystemPrompt() {
    return [
'You are the Research Planner LLM inside an AI writing software.',
'Your only job is to decide which eligible outline sections deserve live source retrieval, what kind of research each needs, and the exact search query to send.',
'Tavily is only the retrieval tool. Do not write research notes. Do not search every section. Do not create article copy.',
'Return valid JSON only.'
    ].join('\n');
  }

  function buildResearchPlanUserPrompt(payload) {
    payload = payload || {};
    const ac = payload.articleContext || {};
    const eligible = payload.outline && Array.isArray(payload.outline.eligibleSections)
      ? payload.outline.eligibleSections
      : [];
    const budgets = planBudgets(payload);
    const compactEligible = eligible.map((s) => ({
      sectionId: s.sectionId,
      headingId: s.headingId,
      sectionHeading: s.headingTitle,
      headingLevel: s.headingLevel,
      parentHeadingTitle: s.parentHeadingTitle || null,
      isIntro: !!s.isIntro,
      talkingPoints: s.talkingPoints || []
    }));
    return [
'Create a targeted research plan for live web/source retrieval.',
'',
'Return exactly this JSON shape:',
'{ "plannedQueries": [ { "sectionId": "string", "headingId": "string", "sectionHeading": "string", "researchNeed": "statistic | benchmark | industry_report | trend | product_fact", "searchQuery": "string", "reason": "string" } ] }',
'',
'Rules:',
'- Plan at most ' + budgets.maxQueries + ' queries.',
'- Do not plan a query for every section by default.',
'- Use only sectionId and headingId values from eligibleSections.',
'- Do not include Conclusion, Final recommendation, FAQ parent headings, or grouping/navigation sections.',
'- Introduction may be selected only when a strong statistic, benchmark, trend, or industry_report would materially improve the opening.',
'- Do not request definitions, examples, case studies, generic explanations, comparison points, or writing advice.',
'- Prefer sections where a source-backed note would change the quality of the draft.',
'- Search queries should be specific enough for source retrieval, not broad article titles.',
'- If few sections need research, return fewer plannedQueries. If none deserve live research, return an empty array.',
'',
'ARTICLE CONTEXT:',
JSON.stringify({
  topic: ac.topic || null,
  primaryKeyword: ac.primaryKeyword || null,
  postType: ac.postType || null,
  selectedIcpId: ac.selectedIcpId || null,
  selectedIcpName: ac.selectedIcpName || null,
  selectedIcpResolution: ac.selectedIcpResolution || 'none_selected',
  selectedIcp: ac.selectedIcp ? {
    id: ac.selectedIcp.id || ac.selectedIcpId || null,
    name: ac.selectedIcp.name || ac.selectedIcpName || null,
    text: ac.selectedIcp.text || ''
  } : null,
  additionalInformation: ac.additionalInformation || null
}, null, 2),
'',
'ELIGIBLE SECTIONS:',
JSON.stringify(compactEligible, null, 2),
'',
'Return valid JSON only. No markdown, no commentary.'
    ].join('\n');
  }

  function parseResearchPlanResponse(content) {
    let text = content;
    if (text && typeof text === 'object') return normalizeResearchPlanShape(text);
    text = String(text || '').trim().replace(/^```(?:json)?\s*/i, '').replace(/```$/i, '').trim();
    if (text[0] !== '{') {
      const brace = text.indexOf('{');
      const last = text.lastIndexOf('}');
      if (brace !== -1 && last > brace) text = text.slice(brace, last + 1);
    }
    try {
      return normalizeResearchPlanShape(JSON.parse(text));
    } catch (e) {
      return { plannedQueries: [], parseError: true, reason: 'The research planner returned invalid JSON.' };
    }
  }

  function normalizeResearchPlanShape(obj) {
    const list = obj && Array.isArray(obj.plannedQueries) ? obj.plannedQueries : [];
    return { plannedQueries: list };
  }

  function validateResearchPlan(plan, payload) {
    plan = plan || {};
    payload = payload || {};
    const eligible = payload.outline && Array.isArray(payload.outline.eligibleSections)
      ? payload.outline.eligibleSections
      : [];
    const eligibleByHeading = {};
    eligible.forEach((s) => { if (s && s.headingId) eligibleByHeading[s.headingId] = s; });
    const budgets = planBudgets(payload);
    const out = [];
    const rejected = [];
    const seen = {};
    const faqOrConclusion = /\b(faq|frequently asked questions|conclusion|final recommendation|final thoughts?|recap|summary)\b/i;
    (Array.isArray(plan.plannedQueries) ? plan.plannedQueries : []).forEach((raw) => {
      raw = raw || {};
      const headingId = String(raw.headingId || '').trim();
      const section = headingId ? eligibleByHeading[headingId] : null;
      const need = normalizePlanNeed(raw.researchNeed);
      const searchQuery = String(raw.searchQuery || '').trim().replace(/\s+/g, ' ');
      const reason = String(raw.reason || '').trim();
      const reject = (issue) => rejected.push({ headingId: headingId || null, issue: issue });

      if (!section) return reject('not_eligible_section');
      if (faqOrConclusion.test(section.headingTitle || '')) return reject('blocked_section_type');
      if (!need) return reject('invalid_research_need');
      if (section.isIntro && ['statistic', 'benchmark', 'trend', 'industry_report'].indexOf(need) === -1) return reject('intro_need_not_material');
      if (searchQuery.length < 8 || searchQuery.length > 180) return reject('invalid_search_query');
      if (reason.length < 8) return reject('missing_reason');
      const key = headingId + '::' + searchQuery.toLowerCase();
      if (seen[key]) return reject('duplicate_query');
      if (out.length >= budgets.maxQueries) return reject('query_budget_exceeded');
      seen[key] = true;
      out.push({
        sectionId: section.sectionId,
        headingId: section.headingId,
        sectionHeading: section.headingTitle,
        researchNeed: need,
        searchQuery: searchQuery,
        reason: reason
      });
    });
    return {
      valid: out.length > 0,
      plannedQueries: out,
      rejectedQueries: rejected,
      budgets: budgets
    };
  }

  function createResearchPlanningAdapter(options) {
    options = options || {};
    const callLLM = options.callLLM;
    return async function planResearch(payload) {
      if (typeof callLLM !== 'function') {
        return {
          plannedQueries: [],
          validation: { valid: false, plannedQueries: [], rejectedQueries: [], budgets: planBudgets(payload) },
          reason: 'No research planning model is connected.'
        };
      }
      const raw = await callLLM({
        systemPrompt: buildResearchPlanSystemPrompt(),
        userPrompt: buildResearchPlanUserPrompt(payload),
        responseFormat: 'json',
        temperature: 0.1,
        metadata: {
          task: 'research_plan',
          articleId: payload && payload.articleId || null,
          promptVersion: RESEARCH_LLM_PROMPT_VERSION
        }
      });
      const content =
        typeof raw === 'string' ? raw :
        (raw && (raw.text || raw.content || raw.output || raw.json)) != null ? (raw.text || raw.content || raw.output || raw.json) :
        raw;
      const parsed = parseResearchPlanResponse(content);
      const validation = validateResearchPlan(parsed, payload);
      return {
        plannedQueries: validation.plannedQueries,
        validation: validation,
        parseError: !!parsed.parseError,
        reason: parsed.reason || null
      };
    };
  }
  /* ============================================================================
     ADAPTER — provider-neutral. Build prompts, call callLLM, parse. No saving.
  ============================================================================ */
  function createResearchLLMAdapter(options) {
    options = options || {};
    const callLLM = options.callLLM;

    return async function researchLLM(payload) {
      if (typeof callLLM !== 'function') {
        /* No provider-neutral LLM wired — surface a clean, structured result the
           workflow can treat as a no-op rather than fabricating research. */
        return {
          notes: [],
          coverageStatus: 'below_target',
          reason: 'No research model is connected (callLLM was not provided).',
          adapterError: true
        };
      }

      /* enrich payload with source candidates the LLM may cite */
      const ctx = options.ctx || payloadCtxFallback(payload);
      const enriched = Object.assign({}, payload);
      if (!enriched.sourceCandidates) {
        enriched.sourceCandidates = buildSourceCandidatesForResearchLLM(ctx);
      }

      const systemPrompt = buildResearchLLMSystemPrompt();
      const userPrompt = buildResearchLLMUserPrompt(enriched);

      let raw;
      try {
        raw = await callLLM({
          systemPrompt: systemPrompt,
          userPrompt: userPrompt,
          responseFormat: 'json',
          temperature: typeof options.temperature === 'number' ? options.temperature : 0.2,
          metadata: {
            articleId: (payload && payload.articleContext && payload.articleId) || (ctx && ctx.articleId) || null,
            workspaceId: (ctx && ctx.workspaceId) || null,
            task: 'research_notes',
            promptVersion: RESEARCH_LLM_PROMPT_VERSION
          }
        });
      } catch (e) {
        try { console.warn('[Research LLM] callLLM failed:', e); } catch (e2) {}
        return {
          notes: [],
          coverageStatus: 'below_target',
          reason: 'The research model call failed.',
          adapterError: true
        };
      }

      /* callLLM may return a string, { text }, { content }, or the object itself */
      const content =
        typeof raw === 'string' ? raw :
        (raw && (raw.text || raw.content || raw.output || raw.json)) != null ? (raw.text || raw.content || raw.output || raw.json) :
        raw;

      return parseResearchLLMResponse(content);
    };
  }

  /* ---------- exports ---------- */
  Object.assign(RA, {
    RESEARCH_LLM_PROMPT_VERSION,
    buildResearchLLMSystemPrompt,
    buildResearchLLMUserPrompt,
    buildResearchLLMMessages,
    parseResearchLLMResponse,
    buildResearchPlanSystemPrompt,
    buildResearchPlanUserPrompt,
    parseResearchPlanResponse,
    validateResearchPlan,
    createResearchPlanningAdapter,
    createResearchLLMAdapter,
    buildSourceCandidatesForResearchLLM
  });
  /* mirror onto ResearchNotes too, so callers using either namespace find them */
  Object.assign(RN, {
    createResearchLLMAdapter,
    createResearchPlanningAdapter,
    buildResearchLLMMessages,
    buildSourceCandidatesForResearchLLM
  });
})();
