/* Rank Lyx — AI Research Agent / FOUNDATION layer: "Prepare article research context"
   ------------------------------------------------------------------------------
   This module is the FOUNDATION for the Research Agent. It runs entirely before
   any external web research and before any LLM research layer.

   ── What the foundation IS ──────────────────────────────────────────────────────
   It is the clean-context preparer. It collects everything the future Research LLM
   will need and packages it into one neutral "Article Research Context" object:
       • the article brief (with explicit "provided by user" flags)
       • the full outline, with heading order, hierarchy, and talking points
       • brand knowledge + approved internal sources
       • any existing protected research notes
       • a structurally-derived eligibleSections list
       • the coverage rules + allowed note-type vocabulary (as reference data only)

   ── What the foundation IS NOT ──────────────────────────────────────────────────
   It is NOT the researcher. It is NOT an LLM. It does not decide what research a
   section needs, does not suggest statistics / examples / benchmarks / case
   studies / pricing / comparison points, does not assign note types to sections,
   does not rank sections by importance, and does not build the final research
   prompt. ALL of those decisions belong to the Research LLM layer that runs later.

   The foundation may only identify *structural* eligibility (is this heading the
   kind of node that can receive research at all), never *what* research to add.

   ── Persistence note for the real app ──────────────────────────────────────────
   Persistence is simulated with localStorage so the object survives reloads and is
   scoped per user + article (mirroring a Supabase row). The save/load functions are
   thin adapters: swap their bodies for Supabase calls
   (e.g. supabase.from('article_research_context').upsert({...})) and nothing else
   in the app needs to change. The stored shape matches the table you'd want.
*/

(function () {
  const SCHEMA_VERSION = 2;

  /* ----------------------------------------------------------------------------
     Current auth + article identity.
     In the real app these come from Supabase auth + the active project/article.
  ---------------------------------------------------------------------------- */
  const AUTH = {
    userId: 'user_jamie_doyle',
    workspaceId: 'ws_ranklyx_demo'
  };

  function currentArticleId() {
    let id = null;
    try { id = localStorage.getItem('rl.activeArticleId'); } catch (e) {}
    if (!id) {
      id = 'art_' + Date.now().toString(36);
      try { localStorage.setItem('rl.activeArticleId', id); } catch (e) {}
    }
    return id;
  }

  /* ----------------------------------------------------------------------------
     Small, neutral helpers (no research logic).
  ---------------------------------------------------------------------------- */
  const clean = (s) => (s == null ? '' : String(s)).trim();
  const splitList = (s) => clean(s).split(',').map((x) => x.trim()).filter(Boolean);
  const nonEmptyPoints = (points) =>
    (points || []).map((p) => clean(p && p.text)).filter(Boolean);

  /* Titles that mean "this node has no real content yet". */
  const PLACEHOLDER_TITLE_RE =
    /^(new section|new subsection|section heading|untitled|untitled topic|opening block|tbd|placeholder)$/i;

  /* Structural ROLE patterns. Matching these classifies the *kind of heading*
     (a closer, a grouping node, a question hub) — it is NOT a decision about what
     research the section needs. These roles are listed in the eligibility spec as
     structurally ineligible, so the foundation is allowed to recognise them. */
  const CONCLUSION_RE = /\b(conclusion|final thoughts?|wrap(?:ping)? up|closing|final word|the bottom line|bottom line)\b/i;
  const RECAP_RE = /\b(recap|final recap|in summary|to sum up|summary of|tl;?dr)\b/i;
  const FAQ_RE = /\b(faq|faqs|frequently asked questions|people also ask)\b/i;
  const GROUPING_RE = /\b(table of contents|in this (?:article|guide|post)|what (?:we'?ll|you'?ll) cover|overview of|jump to|navigation|contents)\b/i;

  const isPlaceholderTitle = (t) => !clean(t) || PLACEHOLDER_TITLE_RE.test(clean(t));

  /* ----------------------------------------------------------------------------
     INTERNAL SOURCES — brand knowledge + approved libraries.
     Returns STRUCTURED internal sources for the new foundation, while also keeping
     the flat legacy fields the existing Research Notes layer reads, so nothing
     downstream breaks. In the real app each block becomes a Supabase query.
  ---------------------------------------------------------------------------- */
  function loadBrandKnowledge() {
    /* Try a saved store first (lets a future Brand Knowledge screen write here);
       fall back to the seed. */
    let saved = null;
    try {
      const raw = localStorage.getItem('rl.brandKnowledge.' + AUTH.workspaceId);
      if (raw) saved = JSON.parse(raw);
    } catch (e) {}
    if (saved) return saved;

    /* Core brand facts (the "who/what/why" of the workspace). */
    const brandKnowledge = {
      businessDescription:
        'Rank Lyx is an AI content platform that helps SEO and content teams plan, ' +
        'brief, and write search-optimized articles that rank and convert.',
      productsServices: [
        'AI Writer — brief → outline → draft → publish workflow',
        'Keyword & intent research',
        'On-page SEO scoring',
        'Brand Knowledge hub for consistent, on-brand drafts'
      ],
      features: [
        'Search-intent matching on every brief',
        'Editable outline with H2–H6 hierarchy and talking points',
        'Brand voice + knowledge injection into drafts',
        'One-click publish to CMS'
      ],
      pricing: [
        { plan: 'Starter', price: '$29/mo', detail: '10 articles / month' },
        { plan: 'Pro', price: '$79/mo', detail: 'Unlimited articles, brand knowledge' },
        { plan: 'Team', price: '$199/mo', detail: 'Seats, workspaces, approvals' }
      ],
      useCases: [
        'SaaS teams scaling a content engine',
        'Agencies producing client articles at volume',
        'Solo founders doing SEO without a writer'
      ],
      targetCustomers: [
        'SaaS founders', 'Content marketers', 'SEO managers', 'Content agencies'
      ],
      positioningNotes:
        'Position against generic AI writers: Rank Lyx is built for SEO outcomes — ' +
        'intent-matched briefs, structured outlines, and brand-aware drafts, not just text.'
    };

    const approvedCaseStudyLibrary = [
      { id: 'cs_fintech_142', title: 'Fintech startup grew organic traffic 142% in 5 months', metric: '+142% organic sessions', approved: true }
    ];
    const approvedTestimonials = [
      { id: 'tm_b2b_brief', quote: 'Briefs that used to take an hour now take five minutes.', author: 'Head of Content, B2B SaaS', approved: true }
    ];
    const approvedCustomerStories = [
      { id: 'st_4person_3x', story: 'A 4-person SaaS marketing team published 3× more articles per month after switching to Rank Lyx.', approved: true }
    ];
    const approvedImportedPages = [
      /* e.g. approved internal URLs the workspace imported. Empty seed for now. */
    ];

    return {
      /* ---- structured internal sources (new foundation reads these) ---- */
      brandKnowledge,
      approvedCaseStudyLibrary,
      approvedTestimonials,
      approvedCustomerStories,
      approvedImportedPages,

      /* ---- flat legacy fields (existing Research Notes layer reads these) ---- */
      businessDescription: brandKnowledge.businessDescription,
      productsServices: brandKnowledge.productsServices,
      features: brandKnowledge.features,
      pricing: brandKnowledge.pricing,
      useCases: brandKnowledge.useCases,
      targetCustomers: brandKnowledge.targetCustomers,
      positioningNotes: brandKnowledge.positioningNotes,
      caseStudies: approvedCaseStudyLibrary,
      customerStories: approvedCustomerStories.map((s) => s.story),
      testimonials: approvedTestimonials.map((t) => ({ quote: t.quote, author: t.author }))
    };
  }

  /* Collect just the structured internal-sources block for the context object. */
  function collectInternalSources(brand) {
    brand = brand || loadBrandKnowledge();
    return {
      brandKnowledge: brand.brandKnowledge || null,
      approvedCaseStudyLibrary: brand.approvedCaseStudyLibrary || [],
      approvedTestimonials: brand.approvedTestimonials || [],
      approvedCustomerStories: brand.approvedCustomerStories || [],
      approvedImportedPages: brand.approvedImportedPages || []
    };
  }

  /* ----------------------------------------------------------------------------
     SEARCH INTENT — neutral article-context helper. Describes how the reader
     arrives at the article; it is NOT a research recommendation. Never throws,
     and falls back to a neutral value the LLM can refine when postType is missing.
  ---------------------------------------------------------------------------- */
  function deriveSearchIntent(postType) {
    const t = clean(postType).toLowerCase();
    if (!t) {
      return 'Unknown or mixed intent. The Research LLM should infer intent from the topic, primary keyword, outline, and talking points.';
    }
    if (t === 'guide')
      return 'Informational — the reader wants to learn how to do or understand something and expects a thorough, well-structured guide.';
    if (t === 'product roundup')
      return 'Commercial investigation — the reader is comparing several options and wants a curated, opinionated list before choosing.';
    if (t === 'product comparison')
      return 'Commercial investigation — the reader is weighing two or more specific options and wants a clear, side-by-side verdict.';
    if (t === 'single product review')
      return 'Commercial / transactional — the reader is close to a decision on one product and wants an honest, detailed assessment.';
    return 'Informational — the reader is researching the topic and wants a clear, credible answer.';
  }

  /* ----------------------------------------------------------------------------
     OUTLINE FLATTENING — preserve order, hierarchy, IDs, and talking points.
     Returns ALL sections in article order: Introduction, H2s, H3s, and any
     H4–H6 that exist. Eligibility is computed separately (see getEligibleSections);
     this function makes no research decisions.

     Section base shape (per spec):
       { headingId, sectionId, headingTitle, headingLevel, parentHeadingId,
         parentHeadingTitle, order, talkingPoints, isIntro, hasChildren,
         standaloneTalkingPoints }
  ---------------------------------------------------------------------------- */
  function flattenOutlineForResearch(outline) {
    const out = [];
    let order = 0;

    (outline || []).forEach((s) => {
      if (s.intro) {
        const tp = nonEmptyPoints(s.points);
        const introId = s.id || 'intro';
        out.push({
          headingId: introId,
          sectionId: introId,
          headingTitle: 'Introduction',
          headingLevel: 'intro',
          parentHeadingId: null,
          parentHeadingTitle: null,
          order: order++,
          talkingPoints: tp,
          isIntro: true,
          hasChildren: false,
          standaloneTalkingPoints: tp
        });
        return;
      }

      const children = Array.isArray(s.children) ? s.children : [];
      const ownPoints = nonEmptyPoints(s.points);
      const parentTitle = clean(s.text);

      /* H2 (parent or standalone) */
      out.push({
        headingId: s.id,
        sectionId: s.id,
        headingTitle: parentTitle,
        headingLevel: 2,
        parentHeadingId: null,
        parentHeadingTitle: null,
        order: order++,
        talkingPoints: ownPoints,
        isIntro: false,
        hasChildren: children.length > 0,
        standaloneTalkingPoints: ownPoints
      });

      /* Children: H3–H6, preserving their own level + parent linkage. */
      children.forEach((c) => {
        const cp = nonEmptyPoints(c.points);
        out.push({
          headingId: c.id,
          sectionId: s.id,            // section the child belongs to = its parent H2
          headingTitle: clean(c.text),
          headingLevel: c.level || 3,
          parentHeadingId: s.id,
          parentHeadingTitle: parentTitle,
          order: order++,
          talkingPoints: cp,
          isIntro: false,
          hasChildren: false,
          standaloneTalkingPoints: cp
        });
      });
    });

    return out;
  }

  /* ----------------------------------------------------------------------------
     STRUCTURAL ELIGIBILITY — the ONLY classification the foundation performs.
     Decides whether a heading is the kind of node that can receive research at
     all. It never decides WHAT research to add, never assigns note types, and
     never ranks sections.

     Eligible:
       1. The Introduction
       2. An H2 with no H3 children
       3. An H3 under an H2
       4. A parent H2 with H3 children ONLY when it has meaningful standalone
          talking points of its own
     Not eligible:
       1. Conclusion        2. Final recap
       3. FAQ parent heading 4. Pure grouping / navigational heading
       5. Parent H2 that only introduces child H3s
       6. Empty, placeholder, or broken section
     (H4–H6 are kept in allSections but are not eligible for research in v1.)
  ---------------------------------------------------------------------------- */
  function evaluateEligibility(sec) {
    /* 1 — Introduction is always eligible when it exists. */
    if (sec.isIntro) {
      return { eligible: true, reason: 'Introduction.' };
    }

    const title = clean(sec.headingTitle);
    const hasOwnPoints = (sec.standaloneTalkingPoints || []).length > 0;

    /* 6 — Empty / placeholder / broken: no real title and no talking points. */
    if (isPlaceholderTitle(title) && !hasOwnPoints) {
      return { eligible: false, reason: 'Empty, placeholder, or broken section.' };
    }

    /* Structural role exclusions (closers / question hubs / grouping). */
    if (CONCLUSION_RE.test(title)) return { eligible: false, reason: 'Conclusion.' };
    if (RECAP_RE.test(title)) return { eligible: false, reason: 'Final recap.' };
    if (FAQ_RE.test(title) && (sec.hasChildren || sec.headingLevel === 2)) {
      return { eligible: false, reason: 'FAQ parent heading.' };
    }
    if (GROUPING_RE.test(title)) {
      return { eligible: false, reason: 'Pure grouping or navigational heading.' };
    }

    /* H3 under an H2 → eligible. H4–H6 → kept but not eligible in v1. */
    if (sec.headingLevel >= 3) {
      if (sec.headingLevel > 3) {
        return { eligible: false, reason: 'Below H3 — not eligible for research in v1.' };
      }
      return { eligible: true, reason: 'H3 under an H2.' };
    }

    /* H2 handling. */
    if (sec.headingLevel === 2) {
      if (!sec.hasChildren) {
        return { eligible: true, reason: 'H2 with no H3 children.' };
      }
      if (hasOwnPoints) {
        return { eligible: true, reason: 'Parent H2 with meaningful standalone talking points.' };
      }
      return { eligible: false, reason: 'Parent H2 that only introduces child H3s.' };
    }

    return { eligible: false, reason: 'Section type not eligible for research in v1.' };
  }

  /* getEligibleSections(allSections)
     Applies ONLY the structural eligibility rules above. Does not recommend
     research, rank sections, or assign note types. Returns eligible-section
     objects (per spec). Accepts the output of flattenOutlineForResearch. */
  function getEligibleSections(allSections) {
    return (allSections || [])
      .filter((sec) => evaluateEligibility(sec).eligible)
      .map((sec) => ({
        headingId: sec.headingId,
        sectionId: sec.sectionId,
        headingTitle: sec.headingTitle,
        headingLevel: sec.headingLevel,
        parentHeadingId: sec.parentHeadingId,
        parentHeadingTitle: sec.parentHeadingTitle,
        order: sec.order,
        talkingPoints: sec.talkingPoints,
        isIntro: sec.isIntro,
        hasChildren: sec.hasChildren,
        standaloneTalkingPoints: sec.standaloneTalkingPoints
      }));
  }

  /* allSections shape (per spec) — base + eligible flag + reason. */
  function annotateAllSections(allSections) {
    return (allSections || []).map((sec) => {
      const e = evaluateEligibility(sec);
      return {
        headingId: sec.headingId,
        sectionId: sec.sectionId,
        headingTitle: sec.headingTitle,
        headingLevel: sec.headingLevel,
        parentHeadingId: sec.parentHeadingId,
        parentHeadingTitle: sec.parentHeadingTitle,
        order: sec.order,
        talkingPoints: sec.talkingPoints,
        isIntro: sec.isIntro,
        hasChildren: sec.hasChildren,
        eligible: e.eligible,
        eligibilityReason: e.reason
      };
    });
  }

  /* ----------------------------------------------------------------------------
     PROTECTED NOTES — existing research notes the user owns and the LLM must not
     overwrite (manual notes, or AI notes the user has edited).
     Reads from the prototype note store; returns [] when none exist.
     Deliberately lightweight — not overbuilt.

     Protected note shape (per spec): { headingId, origin, editedByUser }
  ---------------------------------------------------------------------------- */
  function collectProtectedNotes(userIdOrOpts, articleId) {
    /* Accept both the object form ({ userId, workspaceId, articleId }) used by the
       v1 validation layer and the positional form used internally. */
    let userId, workspaceId, aid;
    if (userIdOrOpts && typeof userIdOrOpts === 'object') {
      userId = userIdOrOpts.userId;
      workspaceId = userIdOrOpts.workspaceId;
      aid = userIdOrOpts.articleId;
    } else {
      userId = userIdOrOpts;
      aid = articleId;
    }
    userId = userId || AUTH.userId;
    workspaceId = workspaceId || AUTH.workspaceId;
    aid = aid || currentArticleId();

    /* Read the v1 research-notes store first, then the legacy store, so protected
       notes are picked up wherever they live. */
    const keys = [
      'rl.articleResearchNotes.' + userId + '.' + workspaceId + '.' + aid,
      'rl.researchNotes.' + userId + '.' + aid
    ];
    const byHeading = {};
    keys.forEach((key) => {
      let record = null;
      try {
        const raw = localStorage.getItem(key);
        if (raw) record = JSON.parse(raw);
      } catch (e) {}
      const notes = (record && Array.isArray(record.notes)) ? record.notes : [];
      notes.forEach((n) => {
        if (!n || !n.headingId) return;
        if (n.deletedAt) return; // soft-deleted notes are not protected
        const origin = n.origin === 'ai' ? 'ai' : 'manual';
        /* Manual notes are user-authored by definition; AI notes count as
           protected only once the user has edited them. */
        const editedByUser = origin === 'manual' ? true : !!n.editedByUser;
        if (origin === 'manual' || editedByUser) {
          byHeading[n.headingId] = { headingId: n.headingId, origin: origin, editedByUser: editedByUser };
        }
      });
    });
    return Object.values(byHeading);
  }

  /* ----------------------------------------------------------------------------
     COVERAGE RULES + ALLOWED NOTE TYPES — reference data only.
     This is the *vocabulary* the future Research LLM may choose from. The
     foundation never picks a type for any section; it only carries the list.
  ---------------------------------------------------------------------------- */
  function buildRules() {
    return {
      coverage: {
        minRatio: 0.33,
        maxRatio: 0.34,
        oneNotePerSection: true
      },
      allowedNoteTypes: [
        'product_fact',
        'statistic',
        'benchmark',
        'industry_report',
        'trend'
      ]
    };
  }

  function researchTextFromHtml(html) {
    const raw = clean(html);
    if (!raw) return '';
    try {
      const div = document.createElement('div');
      div.innerHTML = raw;
      return clean(div.textContent || '');
    } catch (e) {
      return clean(raw.replace(/<[^>]*>/g, ' '));
    }
  }

  function resolveSelectedIcpForResearch(form) {
    const selectedId = clean((form && (form.selectedIcpId || form.targetAudienceId)) || '');
    if (!selectedId) return { id: '', name: '', text: '', resolution: 'none_selected' };
    if (form && form.resolvedIcp && form.resolvedIcp.resolution === 'selected_icp') {
      return {
        id: clean(form.resolvedIcp.id || selectedId),
        name: clean(form.resolvedIcp.name || form.selectedIcpName || ''),
        text: clean(form.resolvedIcp.text || ''),
        resolution: 'selected_icp'
      };
    }
    try {
      const raw = localStorage.getItem('rl.audienceIcpKnowledge');
      const data = raw ? JSON.parse(raw) : {};
      const list = data && Array.isArray(data.icps) ? data.icps : [];
      const match = list.find((icp) => clean(icp && icp.id) === selectedId);
      if (!match) {
        return { id: selectedId, name: clean(form && form.selectedIcpName || ''), text: '', resolution: 'missing_selected_profile_omitted' };
      }
      const strip = window.audStripTemplateHelpers || window.icpStripTemplateHelpers || ((value) => value);
      return {
        id: clean(match.id || selectedId),
        name: clean(match.name || form.selectedIcpName || ''),
        text: researchTextFromHtml(strip(match.details || '')),
        resolution: 'selected_icp'
      };
    } catch (e) {
      return { id: selectedId, name: clean(form && form.selectedIcpName || ''), text: '', resolution: 'missing_selected_profile_omitted' };
    }
  }

  function selectedIcpFromKnowledgeContext(knowledgeContext) {
    const list = knowledgeContext && knowledgeContext.icpKnowledge && Array.isArray(knowledgeContext.icpKnowledge.icps)
      ? knowledgeContext.icpKnowledge.icps
      : [];
    if (!list.length) return { id: '', name: '', text: '', resolution: 'none_selected' };
    return {
      id: clean(list[0].id),
      name: clean(list[0].name),
      text: typeof list[0].text === 'string' ? list[0].text : '',
      resolution: 'selected_icp'
    };
  }

  function snapshotResearchInternalSources(knowledgeContext) {
    const brandProfile = knowledgeContext && knowledgeContext.brandProfile;
    const productKnowledge = knowledgeContext && knowledgeContext.productKnowledge;
    const businessDescription = brandProfile
      ? [brandProfile.brandName ? 'Brand: ' + brandProfile.brandName : '', brandProfile.text || ''].filter(Boolean).join('\n')
      : '';
    const productText = productKnowledge && productKnowledge.text || '';
    const hasBrandKnowledge = !!(businessDescription || productText);
    return {
      brandKnowledge: hasBrandKnowledge ? {
        businessDescription: businessDescription,
        features: productText ? [productText] : [],
        pricing: [],
        useCases: [],
        targetCustomers: [],
        positioningNotes: brandProfile && brandProfile.text || ''
      } : null,
      approvedCaseStudyLibrary: [],
      approvedTestimonials: [],
      approvedCustomerStories: [],
      approvedImportedPages: []
    };
  }

  function normalizeResearchBrief(form, knowledgeContext) {
    const raw = form || {};
    if (knowledgeContext && typeof knowledgeContext === 'object') {
      const selectedIcp = selectedIcpFromKnowledgeContext(knowledgeContext);
      return {
        title: clean(raw.title || raw.topic || ''),
        primaryKeyword: clean(raw.primaryKeyword || raw.keyword || ''),
        postType: clean(raw.postType || raw.contentType || ''),
        additionalInformation: clean(raw.additionalInformation || raw.notes || ''),
        selectedIcpId: selectedIcp.id,
        selectedIcpName: selectedIcp.name,
        resolvedIcp: selectedIcp,
        selectedIcpResolution: selectedIcp.resolution
      };
    }
    let canonical = null;
    if (typeof window !== 'undefined' && typeof window.normalizeBriefForOutline === 'function') {
      try { canonical = window.normalizeBriefForOutline(raw); } catch (e) { canonical = null; }
    }
    const source = canonical || raw;
    const selectedIcp = source.resolvedIcp && source.resolvedIcp.resolution === 'selected_icp'
      ? {
        id: clean(source.resolvedIcp.id || source.selectedIcpId || ''),
        name: clean(source.resolvedIcp.name || source.selectedIcpName || ''),
        text: clean(source.resolvedIcp.text || ''),
        resolution: 'selected_icp'
      }
      : resolveSelectedIcpForResearch(raw);
    return {
      title: clean(source.title || raw.topic || ''),
      primaryKeyword: clean(source.primaryKeyword || raw.keyword || ''),
      postType: clean(source.postType || source.contentType || raw.postType || ''),
      additionalInformation: clean(source.additionalInformation || source.notes || raw.notes || ''),
      selectedIcpId: clean(source.selectedIcpId || raw.selectedIcpId || raw.targetAudienceId || ''),
      selectedIcpName: clean(source.selectedIcpName || raw.selectedIcpName || selectedIcp.name || ''),
      resolvedIcp: selectedIcp,
      selectedIcpResolution: selectedIcp.resolution || 'none_selected'
    };
  }
  /* ----------------------------------------------------------------------------
     CORE — build the Article Research Context object.
     Uses the canonical Brief contract: title, primary keyword, post type,
     additional information, and the selected ICP only. Research does not receive
     unselected ICP profiles, secondary keywords, goal, tone, or Brand Voice.
  ---------------------------------------------------------------------------- */
  function buildArticleResearchContext({ form, outline, articleId, protectedNotes, knowledgeContext }) {
    form = form || {};
    const brief = normalizeResearchBrief(form, knowledgeContext || null);
    const internalSources = knowledgeContext
      ? snapshotResearchInternalSources(knowledgeContext)
      : collectInternalSources(loadBrandKnowledge());
    const explicitArticleId = clean(articleId) || currentArticleId();
    const existingProtectedNotes = Array.isArray(protectedNotes)
      ? protectedNotes
      : collectProtectedNotes({ userId: AUTH.userId, workspaceId: AUTH.workspaceId, articleId: explicitArticleId });

    const flattened = flattenOutlineForResearch(outline);
    const allSections = annotateAllSections(flattened);
    const eligibleSections = getEligibleSections(flattened);
    const headingCount = flattened.filter((s) => s.headingLevel === 2).length;

    /* Brief fields. Required: topic + primaryKeyword. Optional canonical fields
       stay empty when absent; never invent missing research context. */

    const topic = brief.title || null;
    const primaryKeyword = brief.primaryKeyword || null;
    const postType = brief.postType || null;
    const selectedIcp = brief.resolvedIcp || { resolution: 'none_selected' };
    const selectedIcpResolution = brief.selectedIcpResolution || selectedIcp.resolution || 'none_selected';
    const additionalInformation = brief.additionalInformation || null;

    return {
      /* identity / scoping */
      schemaVersion: SCHEMA_VERSION,
      userId: AUTH.userId,
      workspaceId: AUTH.workspaceId,
      articleId: explicitArticleId,
      generatedAt: new Date().toISOString(),

      /* article context — what the article IS, never what research it needs */
      articleContext: {
        topic: topic,
        primaryKeyword: primaryKeyword,
        postType: postType,
        searchIntent: deriveSearchIntent(postType),
        selectedIcpId: brief.selectedIcpId || null,
        selectedIcpName: brief.selectedIcpName || null,
        selectedIcpResolution: selectedIcpResolution,
        selectedIcp: selectedIcpResolution === 'selected_icp' ? {
          id: selectedIcp.id || brief.selectedIcpId || null,
          name: selectedIcp.name || brief.selectedIcpName || null,
          text: selectedIcp.text || ''
        } : null,

        additionalInformation: additionalInformation,
        additionalInformationProvidedByUser: !!additionalInformation
      },

      /* outline context — order + hierarchy preserved, structural eligibility only */
      outlineContext: {
        outlineSnapshot: outline || [],
        headingCount: headingCount,
        eligibleSectionCount: eligibleSections.length,
        eligibleSections: eligibleSections,
        allSections: allSections
      },

      /* internal sources — brand knowledge + approved libraries */
      internalSources: internalSources,

      /* normalized, validated Article Knowledge for prompt injection */
      knowledgeContext: knowledgeContext || null,

      /* existing protected notes the LLM must not overwrite */
      protectedNotes: existingProtectedNotes,

      /* reference rules + allowed note-type vocabulary (carried, never applied) */
      rules: buildRules(),

      /* raw inputs captured so later steps can reuse them verbatim */
      sourceInputs: {
        brief: {
          topic: topic,
          primaryKeyword: primaryKeyword,
          postType: postType,
          selectedIcpId: brief.selectedIcpId || null,
          selectedIcpName: brief.selectedIcpName || null,
          selectedIcpResolution: selectedIcpResolution,
          additionalInformation: additionalInformation,
          additionalInformationProvidedByUser: !!additionalInformation
        },
        outline: outline || [],
        brandKnowledgeUsed: !!(internalSources && internalSources.brandKnowledge)
      }
    };
  }

  /* ----------------------------------------------------------------------------
     RESEARCH LLM PAYLOAD — a clean, neutral package for the FUTURE Research LLM.
     Carries article context, structurally-eligible sections, internal sources,
     protected notes, the coverage rules, and a plain output-contract summary.
     It contains NO per-section recommendations and NO instruction that a specific
     section needs a specific research type — every such decision is the LLM's.
  ---------------------------------------------------------------------------- */
  function buildResearchLLMPayload(ctx) {
    ctx = ctx || {};
    const oc = ctx.outlineContext || {};
    const rules = ctx.rules || buildRules();

    return {
      schemaVersion: ctx.schemaVersion || SCHEMA_VERSION,
      generatedAt: new Date().toISOString(),

      articleContext: ctx.articleContext || null,

      outline: {
        headingCount: oc.headingCount || 0,
        eligibleSectionCount: oc.eligibleSectionCount || 0,
        /* Eligible sections are offered as *candidates*. The LLM decides which of
           them actually receive a note, and what kind — the foundation does not. */
        eligibleSections: oc.eligibleSections || []
      },

      internalSources: ctx.internalSources || null,
      knowledgeContext: ctx.knowledgeContext || null,
      protectedNotes: ctx.protectedNotes || [],

      /* Source candidates the future Research LLM is allowed to cite. Built from
         internal sources only for now (no web research). The foundation merely
         carries them; choosing which to use is the LLM's job. */
      sourceCandidates: (typeof window !== 'undefined' &&
        window.ResearchAgent && window.ResearchAgent.buildSourceCandidatesForResearchLLM)
        ? window.ResearchAgent.buildSourceCandidatesForResearchLLM(ctx)
        : [],

      rules: rules,

      outputContract: {
        summary:
          'Decide, per eligible section, whether it benefits from one supporting ' +
          'research note. Cover roughly one third of eligible sections; ' +
          'at most one note per section. Choose each note type yourself from ' +
          'allowedNoteTypes based on the section content — the foundation has made ' +
          'no such choice. Never overwrite protected notes.',
        coverage: rules.coverage,
        allowedNoteTypes: rules.allowedNoteTypes,
        oneNotePerSection: rules.coverage.oneNotePerSection,
        respectProtectedNotes: true,
        /* Explicit guarantees about what the foundation did NOT do, so the LLM
           knows these decisions are entirely its own. */
        foundationGuarantees: {
          assignedNoteTypes: false,
          recommendedResearchPerSection: false,
          rankedSections: false
        }
      }
    };
  }

  /* ----------------------------------------------------------------------------
     PERSISTENCE — save / load, scoped per user + article.
     Adapter functions: swap the bodies for Supabase upsert/select in the real app.
  ---------------------------------------------------------------------------- */
  function storageKey(userId, articleId) {
    return 'rl.articleResearchContext.' + userId + '.' + articleId;
  }

  function saveArticleResearchContext(ctx) {
    try {
      localStorage.setItem(storageKey(ctx.userId, ctx.articleId), JSON.stringify(ctx));
    } catch (e) {
      /* non-fatal in the prototype */
    }
    try {
      console.info('[Research Agent] Article Research Context saved for', ctx.userId, '/', ctx.articleId);
      console.debug('[Research Agent] context object:', ctx);
    } catch (e) {}
    return ctx;
  }

  function loadArticleResearchContext(userId, articleId) {
    try {
      const raw = localStorage.getItem(
        storageKey(userId || AUTH.userId, articleId || currentArticleId())
      );
      return raw ? JSON.parse(raw) : null;
    } catch (e) {
      return null;
    }
  }

  /* ----------------------------------------------------------------------------
     ORCHESTRATOR — the single call the pre-research step makes.
     Builds the context, saves it, resolves with it. Returns a Promise (with a
     small realistic delay) so a button can show a loading state.
  ---------------------------------------------------------------------------- */
  function understandArticleContext({ form, outline }) {
    return new Promise((resolve) => {
      setTimeout(() => {
        const ctx = buildArticleResearchContext({ form, outline });
        saveArticleResearchContext(ctx);
        resolve(ctx);
      }, 1200);
    });
  }

  /* ---------- exports ---------- */
  window.ResearchAgent = {
    AUTH,
    currentArticleId,
    loadBrandKnowledge,
    deriveSearchIntent,
    flattenOutlineForResearch,
    getEligibleSections,
    collectProtectedNotes,
    buildArticleResearchContext,
    buildResearchLLMPayload,
    saveArticleResearchContext,
    loadArticleResearchContext,
    understandArticleContext
  };
})();
