/* Rank Lyx — AI Research Agent / VALIDATION + REPAIR layer (v1 data contract)
   ------------------------------------------------------------------------------
   This module sits on top of the Research Foundation (research.jsx). It does NOT
   research and does NOT decide what each section needs. It only:

     • defines the v1 Research Note data contract (allowed enums + shape)
     • normalizes SAFE formatting issues on incoming LLM notes
     • validates notes against the contract + the Article Research Context
     • builds a repair payload and runs exactly ONE repair attempt
     • saves only valid notes, in a store kept separate from the outline

   The foundation may reject bad LLM output and ask the LLM to repair it once.
   The foundation must never decide WHAT research to add, choose between duplicate
   notes, invent sources/dates, or change a note's type/section by opinion.

   Augments window.ResearchAgent with the v1 contract, validators, repair, and the
   research-notes storage adapters. Load AFTER research.jsx.
*/

(function () {
  const RA = window.ResearchAgent || (window.ResearchAgent = {});
  const AUTH = RA.AUTH || { userId: 'user_jamie_doyle', workspaceId: 'ws_ranklyx_demo' };

  const RESEARCH_NOTE_SCHEMA_VERSION = 1;

  /* ---- allowed enums (the v1 contract vocabulary) ---- */
  const ALLOWED_RESEARCH_NOTE_TYPES = [
    'product_fact', 'statistic', 'benchmark', 'industry_report', 'trend'
  ];
  const ALLOWED_SOURCE_RELATIONSHIPS = [
    'approved_internal', 'approved_case_study_library', 'trusted_external',
    'official_product_page', 'official_pricing_page', 'community_reddit',
    'community_quora', 'non_competing_brand', 'competitor', 'unknown'
  ];
  const ALLOWED_COMPETITOR_RISKS = ['none', 'low', 'medium', 'high'];
  const ALLOWED_EXAMPLE_KINDS = [null];
  const VALID_HEADING_LEVELS = ['intro', 2, 3];

  /* note types that are inherently time-sensitive */
  const TIME_SENSITIVE_TYPES = [
    'statistic', 'benchmark', 'industry_report', 'trend'
  ];
  /* time-sensitive types that REQUIRE a source date */
  const DATE_REQUIRED_TYPES = ['statistic', 'benchmark', 'industry_report', 'trend'];
  /* community sources can never back hard numeric claims */
  const COMMUNITY_FORBIDDEN_TYPES = [
    'statistic', 'benchmark', 'product_fact', 'industry_report'
  ];
  /* article types where competitor discussion is expected */
  const COMPARISON_POST_TYPES =
    /(comparison|roundup|alternatives?|best\s+(tools|software|apps)|vs\b|versus)/i;

  /* generic whyItMatters lines to reject */
  const GENERIC_WHY = [
    'this is useful for the article',
    'this helps improve credibility',
    'this gives more context',
    'this makes the article better',
    'useful for the article',
    'improves credibility',
    'adds context',
    'good for seo',
    'helps the reader'
  ];

  /* ----------------------------------------------------------------------------
     small helpers
  ---------------------------------------------------------------------------- */
  const clean = (s) => (s == null ? '' : String(s)).trim();
  const isStr = (s) => typeof s === 'string' && s.trim().length > 0;
  const genId = () => 'note_' + Date.now().toString(36) + '_' + Math.random().toString(36).slice(2, 7);
  const nowIso = () => new Date().toISOString();
  const RECENCY_WINDOW_MONTHS = 24;
  const NOTE_TYPE_ALIASES = {
    statistic: 'statistic',
    statistics: 'statistic',
    stat: 'statistic',
    benchmark: 'benchmark',
    benchmarks: 'benchmark',
    'industry report': 'industry_report',
    industry_report: 'industry_report',
    report: 'industry_report',
    trend: 'trend',
    trends: 'trend',
    'product fact': 'product_fact',
    product_fact: 'product_fact',
    product: 'product_fact',
    'pricing fact': null,
    pricing_fact: null,
    'comparison point': null,
    comparison_point: null,
    example: null,
    'case study': null,
    case_study: null,
    definition: null
  };

  function sentencesOf(text) {
    return clean(text).split(/[.!?]+/).map((s) => s.trim()).filter(Boolean);
  }
  function wordsOf(text) {
    return clean(text).split(/\s+/).filter(Boolean);
  }
  function internalSourceAnchorTerms(internalSources) {
    internalSources = internalSources || {};
    const brand = internalSources.brandKnowledge || {};
    const terms = [];
    const addTerm = (value) => {
      const term = clean(value).toLowerCase();
      if (term && term.length >= 4 && terms.indexOf(term) === -1) terms.push(term);
    };
    addTerm('Rank Lyx');
    (brand.productsServices || []).forEach((item) => addTerm(String(item || '').split(/[—-]/)[0]));
    (brand.features || []).forEach((item) => addTerm(item));
    addTerm(brand.businessDescription);
    addTerm(brand.positioningNotes);
    return terms.filter((term) => term.split(/\s+/).length <= 8);
  }
  function hasInternalSourceAnchor(note, internalSources) {
    const text = [
      note && note.headingTitle,
      note && note.note,
      note && note.whyItMatters,
      note && note.sourcePublisher,
      note && note.sourceTitle
    ].map(clean).join(' ').toLowerCase();
    return internalSourceAnchorTerms(internalSources).some((term) => text.indexOf(term) !== -1);
  }
  function isComparisonArticle(articleContext) {
    const pt = clean(articleContext && articleContext.postType);
    return COMPARISON_POST_TYPES.test(pt);
  }
  /* canonical-case match against an allowed list (case-insensitive) */
  function canonical(value, list) {
    const v = clean(value).toLowerCase();
    for (let i = 0; i < list.length; i++) {
      if (list[i] != null && String(list[i]).toLowerCase() === v) return list[i];
    }
    return null;
  }
  function canonicalNoteType(value) {
    const raw = clean(value);
    const key = raw.toLowerCase().replace(/[\s-]+/g, '_');
    if (Object.prototype.hasOwnProperty.call(NOTE_TYPE_ALIASES, key)) return NOTE_TYPE_ALIASES[key];
    const spaced = raw.toLowerCase().replace(/[_-]+/g, ' ');
    if (Object.prototype.hasOwnProperty.call(NOTE_TYPE_ALIASES, spaced)) return NOTE_TYPE_ALIASES[spaced];
    return canonical(value, ALLOWED_RESEARCH_NOTE_TYPES);
  }
  function resolveNow(ctx, opts) {
    const raw = (opts && (opts.now || opts.currentDate)) || (ctx && (ctx.now || ctx.currentDate));
    const d = raw ? new Date(raw) : new Date();
    return isNaN(d.getTime()) ? new Date() : d;
  }
  function parseSourceDate(value) {
    const s = clean(value);
    if (!s) return null;
    let m = s.match(/\b(19|20)\d{2}-\d{2}-\d{2}\b/);
    if (m) {
      const d = new Date(m[0] + 'T00:00:00Z');
      return isNaN(d.getTime()) ? null : d;
    }
    m = s.match(/\b((19|20)\d{2})-(\d{2})\b/);
    if (m) {
      const d = new Date(m[1] + '-' + m[3] + '-01T00:00:00Z');
      return isNaN(d.getTime()) ? null : d;
    }
    m = s.match(/\b((19|20)\d{2})\b/);
    if (m) {
      const d = new Date(m[1] + '-01-01T00:00:00Z');
      return isNaN(d.getTime()) ? null : d;
    }
    return null;
  }
  function monthsBetween(later, earlier) {
    return (later.getUTCFullYear() - earlier.getUTCFullYear()) * 12 +
      (later.getUTCMonth() - earlier.getUTCMonth()) +
      ((later.getUTCDate() >= earlier.getUTCDate()) ? 0 : -1);
  }
  function sourceDateWithinRollingWindow(sourceDate, now) {
    const d = parseSourceDate(sourceDate);
    if (!d) return false;
    if (d.getTime() > now.getTime() + 24 * 60 * 60 * 1000) return false;
    return monthsBetween(now, d) <= RECENCY_WINDOW_MONTHS;
  }
  function productFactLooksTimeSensitive(note) {
    const text = [note && note.note, note && note.sourceTitle, note && note.headingTitle].map(clean).join(' ');
    return /\b(\d+%|\$\d+|\d+\s*(users|customers|teams|seats|agents|plans|days|months|years)|pricing|price|cost|plan|tier|rank|ranking|best|top|market share|revenue|growth|in\s+20\d{2}|202\d)\b/i.test(text);
  }
  function coverageBudget(eligibleCount) {
    eligibleCount = Math.max(0, Number(eligibleCount) || 0);
    if (!eligibleCount) return { minNotes: 0, maxNotes: 0 };
    const minNotes = Math.max(1, Math.floor(eligibleCount / 3));
    const maxNotes = Math.max(minNotes, Math.ceil(eligibleCount / 3));
    return { minNotes: minNotes, maxNotes: maxNotes };
  }

  /* ----------------------------------------------------------------------------
     LEGACY BRIDGE — the Outline screen renders sourceName / pubYear / sourceType.
     Map old↔new so existing notes display and new notes stay readable.
  ---------------------------------------------------------------------------- */
  const RELATIONSHIP_SOURCE_TYPE = {
    approved_internal: 'Brand Knowledge',
    approved_case_study_library: 'Brand Knowledge',
    non_competing_brand: 'Brand Knowledge'
  };
  function applyLegacyAliases(note) {
    /* add the fields the current Outline note UI reads, without losing v1 fields */
    const out = Object.assign({}, note);
    if (out.sourceName == null) out.sourceName = out.sourcePublisher || out.sourceTitle || null;
    if (out.pubYear == null) {
      const d = clean(out.sourceDate);
      const m = d.match(/\b(19|20)\d{2}\b/);
      out.pubYear = m ? m[0] : null;
    }
    if (out.sourceType == null) {
      out.sourceType = RELATIONSHIP_SOURCE_TYPE[out.sourceRelationship] || 'External web source';
    }
    return out;
  }
  function absorbLegacyFields(note) {
    /* if an incoming note only carries legacy fields, lift them into v1 fields */
    const out = Object.assign({}, note);
    if (out.sourcePublisher == null && note.sourceName != null) out.sourcePublisher = note.sourceName;
    if (out.sourceTitle == null && note.sourceName != null) out.sourceTitle = note.sourceName;
    if (out.sourceDate == null && note.pubYear != null) out.sourceDate = String(note.pubYear);
    return out;
  }

  /* ----------------------------------------------------------------------------
     NORMALIZE — SAFE formatting only. Never fixes judgment errors.
  ---------------------------------------------------------------------------- */
  function normalizeResearchNote(note, ctx) {
    if (!note || typeof note !== 'object') return note;
    let n = absorbLegacyFields(note);
    n = Object.assign({}, n);

    /* trim string fields */
    ['note', 'whyItMatters', 'headingTitle', 'sourcePublisher', 'sourceUrl',
     'sourceTitle', 'sourceDate', 'headingId', 'sectionId', 'articleId']
      .forEach((k) => { if (typeof n[k] === 'string') n[k] = n[k].trim(); });

    /* normalize enum casing when an unambiguous match exists */
    const ct = canonicalNoteType(n.noteType);
    if (ct) n.noteType = ct;
    const cr = canonical(n.competitorRisk, ALLOWED_COMPETITOR_RISKS);
    if (cr) n.competitorRisk = cr;
    const sr = canonical(String(n.sourceRelationship || '').replace(/[\s-]+/g, '_'), ALLOWED_SOURCE_RELATIONSHIPS);
    if (sr) n.sourceRelationship = sr;

    /* derive heading identity from the matched eligible section (deterministic,
       not a judgment call) */
    if (ctx && ctx.outlineContext) {
      const sec = (ctx.outlineContext.eligibleSections || []).find((s) => s.headingId === n.headingId);
      if (sec) {
        if (n.sectionId == null) n.sectionId = sec.sectionId;
        if (n.headingTitle == null) n.headingTitle = sec.headingTitle;
        if (n.headingLevel == null) n.headingLevel = sec.headingLevel;
      }
      if (n.articleId == null) n.articleId = ctx.articleId;
    }

    /* unconditional safe defaults */
    if (n.origin !== 'manual') n.origin = n.origin === 'ai' ? 'ai' : 'ai';
    if (n.origin === 'ai' && n.editedByUser == null) n.editedByUser = false;
    if (n.updatedAt === undefined) n.updatedAt = null;
    if (n.deletedAt === undefined) n.deletedAt = null;
    if (n.exampleKind === undefined) n.exampleKind = null;
    if (n.sourcePublisher === undefined) n.sourcePublisher = null;
    if (n.sourceUrl === undefined) n.sourceUrl = null;
    if (n.sourceTitle === undefined) n.sourceTitle = null;
    if (n.sourceDate === undefined) n.sourceDate = null;

    return n;
  }

  /* ----------------------------------------------------------------------------
     VALIDATE ONE NOTE — against the contract + Article Research Context.
     opts: { eligibleIndex, protectedIndex, postType, internalSources, isAiBatch }
     Returns { valid, note, errors:[{noteId,headingId,issue,instruction}], warnings:[] }
  ---------------------------------------------------------------------------- */
  function validateResearchNote(rawNote, ctx, opts) {
    opts = opts || {};
    const eligibleIndex = opts.eligibleIndex || buildEligibleIndex(ctx);
    const protectedIndex = opts.protectedIndex || buildProtectedIndex(ctx);
    const internalSources = opts.internalSources || (ctx && ctx.internalSources) || {};
    const postType = opts.postType || (ctx && ctx.articleContext && ctx.articleContext.postType) || null;
    const isAiBatch = opts.isAiBatch !== false;
    const now = resolveNow(ctx, opts);

    const n = normalizeResearchNote(rawNote, ctx);
    const headingId = (n && n.headingId) || null;
    const errors = [];
    const warnings = [];
    const add = (issue, instruction) =>
      errors.push({ noteId: (n && n.id) || null, headingId: headingId, issue: issue, instruction: instruction });

    /* 17 — already-deleted notes are not saved (unless migrating) */
    if (n.deletedAt) {
      add('already_deleted', 'Do not submit notes that are already deleted.');
    }

    /* 1 — schema: required content/judgment fields must be present */
    const requiredContent = ['headingId', 'noteType', 'note', 'whyItMatters', 'sourceRelationship', 'competitorRisk', 'origin'];
    requiredContent.forEach((f) => {
      if (!isStr(n[f]) && !(f === 'noteType' && n[f])) {
        if (n[f] == null || n[f] === '') add('missing_field:' + f, 'Provide the required field "' + f + '".');
      }
    });
    if (typeof n.isTimeSensitive !== 'boolean') {
      add('missing_field:isTimeSensitive', 'Set isTimeSensitive to true or false.');
    }

    /* 2 — allowed note type */
    if (!ALLOWED_RESEARCH_NOTE_TYPES.includes(n.noteType)) {
      add('invalid_note_type', 'Use exactly one approved note type: ' + ALLOWED_RESEARCH_NOTE_TYPES.join(', ') + '.');
    }

    /* 3 — eligible section + valid heading level */
    const section = headingId ? eligibleIndex[headingId] : null;
    if (!section) {
      add('not_eligible_section', 'Attach the note to an eligible section only (Introduction, an H2 with no children, or an H3 under an H2).');
    } else if (VALID_HEADING_LEVELS.indexOf(section.headingLevel) === -1) {
      add('invalid_heading_level', 'Only intro, H2, and H3 sections can receive research in v1.');
    }

    /* 16 — origin: the research LLM must not author manual notes */
    if (isAiBatch && n.origin === 'manual') {
      add('invalid_manual_origin', 'The research LLM must not create manual notes; set origin to "ai".');
    }
    if (n.origin !== 'ai' && n.origin !== 'manual') {
      add('invalid_origin', 'origin must be "ai" or "manual".');
    }

    /* 15 — source relationship must be approved; "unknown" rules */
    if (!ALLOWED_SOURCE_RELATIONSHIPS.includes(n.sourceRelationship)) {
      add('invalid_source_relationship', 'sourceRelationship must be one of: ' + ALLOWED_SOURCE_RELATIONSHIPS.join(', ') + '.');
    }
    if (n.sourceRelationship === 'unknown') {
      const okUnknown = n.origin === 'manual';
      if (!okUnknown || n.isTimeSensitive) {
        add('invalid_unknown_relationship', '"unknown" source relationship is only allowed for manual notes, never for AI research.');
      }
    }

    if (n.sourceRelationship === 'approved_internal' && !hasInternalSourceAnchor(n, internalSources)) {
      add('unanchored_internal_source', 'approved_internal can only support claims clearly anchored to supplied internal brand/product knowledge. Do not use it for third-party product facts or generic external claims.');
    }

    /* 14 — competitor risk */
    if (!ALLOWED_COMPETITOR_RISKS.includes(n.competitorRisk)) {
      add('invalid_competitor_risk', 'competitorRisk must be one of: ' + ALLOWED_COMPETITOR_RISKS.join(', ') + '.');
    }
    if (n.competitorRisk === 'high') {
      add('competitor_risk_high', 'Remove notes with high competitor risk.');
    } else if (n.competitorRisk === 'medium' && !COMPARISON_POST_TYPES.test(clean(postType))) {
      add('competitor_risk_medium', 'Medium competitor risk is only allowed for comparison-style articles (Comparison, Roundup, Alternatives, Best Tools/Software). Remove or replace this note.');
    }
    /* 7 — note length: 1–3 sentences, ≤20 words/sentence, ≤60 words total */
    if (isStr(n.note)) {
      const sents = sentencesOf(n.note);
      const total = wordsOf(n.note).length;
      const longSentence = sents.some((s) => wordsOf(s).length > 20);
      if (sents.length < 1 || sents.length > 3 || total > 60 || longSentence) {
        add('note_too_long', 'Rewrite the note to 1 to 3 sentences, maximum 20 words per sentence, maximum 60 words total. Keep the meaning and source.');
      }
    }

    /* 8 — whyItMatters: present, 1–2 specific sentences, not generic */
    if (!isStr(n.whyItMatters)) {
      add('missing_why', 'Add whyItMatters: 1–2 specific sentences on how the Writing Agent should use this note.');
    } else {
      const why = n.whyItMatters.toLowerCase().replace(/[.?!]/g, '').trim();
      const generic = GENERIC_WHY.some((g) => why === g || why.indexOf(g) !== -1 && why.length < g.length + 8);
      const sents = sentencesOf(n.whyItMatters);
      if (generic) {
        add('weak_why', 'Rewrite whyItMatters to be specific about how the Writing Agent should use this note, not a generic credibility line.');
      } else if (sents.length > 2) {
        add('why_too_long', 'Keep whyItMatters to 1–2 short sentences.');
      }
    }

    /* 9 — source presence */
    const sourceOptional = n.sourceRelationship === 'approved_internal';
    if (!sourceOptional && !isStr(n.sourceUrl)) {
      add('missing_source', 'External research needs a real source URL, publisher, and title.');
    }
    if (!sourceOptional && isStr(n.sourceUrl) && (!isStr(n.sourcePublisher) || !isStr(n.sourceTitle))) {
      add('incomplete_source', 'Add both sourcePublisher and sourceTitle alongside the source URL.');
    }

    /* 10 — time-sensitive date requirements */
    const officialLive = n.sourceRelationship === 'official_product_page' || n.sourceRelationship === 'official_pricing_page';
    if (DATE_REQUIRED_TYPES.indexOf(n.noteType) !== -1 && !isStr(n.sourceDate) && !officialLive) {
      add('missing_source_date', 'Add the source date for this time-sensitive claim (statistic/benchmark/industry_report/trend), or skip the note.');
    }
    const productFactNeedsDate = n.noteType === 'product_fact' && !officialLive && !sourceOptional &&
      (n.isTimeSensitive || productFactLooksTimeSensitive(n));
    if (productFactNeedsDate && !isStr(n.sourceDate)) {
      add('missing_source_date', 'Add a source date for this time-sensitive product fact, or use an official live product/pricing page.');
    }
    const datedTypeNeedsRecency = DATE_REQUIRED_TYPES.indexOf(n.noteType) !== -1 || productFactNeedsDate;
    if (datedTypeNeedsRecency && isStr(n.sourceDate) && !officialLive && !sourceDateWithinRollingWindow(n.sourceDate, now)) {
      add('outdated_source', 'Use a source published or updated within the last 24 months from today, or skip the note.');
    }


    /* 13 — Reddit / Quora cannot back hard numeric claims */
    if (n.sourceRelationship === 'community_reddit' || n.sourceRelationship === 'community_quora') {
      if (COMMUNITY_FORBIDDEN_TYPES.indexOf(n.noteType) !== -1) {
        add('invalid_community_source', 'Reddit and Quora can only support trend notes framed as user signals, not statistics, benchmarks, product facts, or reports.');
      }
    }

    /* 17 — createdAt must be ISO if present */
    if (n.createdAt != null && isNaN(Date.parse(n.createdAt))) {
      add('invalid_created_at', 'createdAt must be an ISO timestamp.');
    }

    /* Finalize: only auto-fill id/createdAt when EVERYTHING ELSE is valid. */
    let finalNote = n;
    if (errors.length === 0) {
      finalNote = Object.assign({}, n);
      finalNote.schemaVersion = RESEARCH_NOTE_SCHEMA_VERSION;
      if (!isStr(finalNote.id)) finalNote.id = genId();
      if (!isStr(finalNote.createdAt)) finalNote.createdAt = nowIso();
      if (finalNote.updatedAt === undefined) finalNote.updatedAt = null;
      if (finalNote.deletedAt === undefined) finalNote.deletedAt = null;
      finalNote = applyLegacyAliases(finalNote);
    }

    return { valid: errors.length === 0, note: finalNote, errors: errors, warnings: warnings };
  }

  /* ----------------------------------------------------------------------------
     index builders
  ---------------------------------------------------------------------------- */
  function buildEligibleIndex(ctx) {
    const idx = {};
    const list = (ctx && ctx.outlineContext && ctx.outlineContext.eligibleSections) || [];
    list.forEach((s) => { idx[s.headingId] = s; });
    return idx;
  }
  function buildProtectedIndex(ctx) {
    const idx = {};
    let list = (ctx && ctx.protectedNotes) || [];
    /* always also re-read the live store so freshly-saved notes count */
    if (RA.collectProtectedNotes && ctx) {
      try {
        list = list.concat(RA.collectProtectedNotes({
          userId: ctx.userId, workspaceId: ctx.workspaceId, articleId: ctx.articleId
        }));
      } catch (e) {}
    }
    list.forEach((p) => { if (p && p.headingId) idx[p.headingId] = p; });
    return idx;
  }

  /* ----------------------------------------------------------------------------
     VALIDATE RESPONSE — full LLM response { notes, coverageStatus, reason }.
     Adds duplicate detection, protected/occupied handling, and coverage.
  ---------------------------------------------------------------------------- */
  function validateResearchResponse(response, ctx) {
    response = response || {};
    const rawNotes = Array.isArray(response.notes) ? response.notes : [];
    const eligibleIndex = buildEligibleIndex(ctx);
    const protectedIndex = buildProtectedIndex(ctx);
    const occupiedIndex = buildOccupiedIndex(ctx);
    const postType = ctx && ctx.articleContext && ctx.articleContext.postType;
    const internalSources = (ctx && ctx.internalSources) || {};

    const errors = [];
    const warnings = [];
    const validNotes = [];
    const invalidNotes = [];

    /* per-note validation */
    const perNote = rawNotes.map((raw) =>
      validateResearchNote(raw, ctx, { eligibleIndex, protectedIndex, occupiedIndex, postType, internalSources, isAiBatch: true })
    );

    /* 4 — duplicate headingIds within the response → invalid, no silent pick */
    const headingCounts = {};
    perNote.forEach((r) => {
      const h = r.note && r.note.headingId;
      if (h) headingCounts[h] = (headingCounts[h] || 0) + 1;
    });

    perNote.forEach((r) => {
      const note = r.note;
      const headingId = note && note.headingId;
      const noteErrors = r.errors.slice();
      r.warnings.forEach((w) => warnings.push(w));

      /* duplicate within response */
      if (headingId && headingCounts[headingId] > 1) {
        noteErrors.push({
          noteId: (note && note.id) || null, headingId: headingId, issue: 'duplicate_in_response',
          instruction: 'Only one research note is allowed per heading. Choose the strongest note and remove the other.'
        });
      }

      /* 6 — protected conflict → DROP (warning), do not repair */
      if (headingId && protectedIndex[headingId]) {
        warnings.push({
          noteId: (note && note.id) || null, headingId: headingId, issue: 'protected_conflict',
          detail: 'Heading already has a protected (manual or user-edited) note; AI note dropped, not repaired.'
        });
        invalidNotes.push({ note: note, errors: [{ headingId: headingId, issue: 'protected_conflict', instruction: 'Do not write to a protected heading.' }] });
        return;
      }

      /* section already has an active note → fill-missing means drop (warning) */
      if (headingId && occupiedIndex[headingId]) {
        warnings.push({
          noteId: (note && note.id) || null, headingId: headingId, issue: 'section_occupied',
          detail: 'Heading already has an active note; AI note skipped under fill_missing_only.'
        });
        invalidNotes.push({ note: note, errors: [{ headingId: headingId, issue: 'section_occupied', instruction: 'Only write to headings without an existing active note.' }] });
        return;
      }

      if (noteErrors.length === 0) {
        validNotes.push(note);
      } else {
        invalidNotes.push({ note: note, errors: noteErrors });
        noteErrors.forEach((e) => errors.push(e));
      }
    });

    /* 5 — coverage */
    const eligibleCount = Object.keys(eligibleIndex).length;
    const budgets = coverageBudget(eligibleCount);
    const minNotes = budgets.minNotes;
    const maxNotes = budgets.maxNotes;
    const returnedCount = rawNotes.length;
    const coverageStatus = clean(response.coverageStatus) || null;
    const reason = clean(response.reason) || null;

    let status = 'within_target';
    if (returnedCount > maxNotes) {
      status = 'over_target';
      errors.push({ noteId: null, headingId: null, issue: 'coverage_over',
        instruction: 'Return at most ' + maxNotes + ' notes (roughly one third of eligible sections). Keep only the strongest.' });
    } else if (returnedCount < minNotes) {
      const reasonOk = coverageStatus === 'below_target' && reason &&
        /(weak|risky|outdated|unsourced|no source|irrelevant|insufficient|not enough|low quality|thin)/i.test(reason);
      if (reasonOk) {
        status = 'below_target';
        warnings.push({ noteId: null, headingId: null, issue: 'coverage_below_justified', detail: reason });
      } else {
        status = 'below_target_unjustified';
        errors.push({ noteId: null, headingId: null, issue: 'coverage_under',
          instruction: 'Return at least ' + minNotes + ' notes, OR set coverageStatus "below_target" with a specific reason (weak/risky/outdated/unsourced/irrelevant research). Do not force weak research to hit the minimum.' });
      }
    }

    return {
      valid: errors.length === 0,
      validNotes: validNotes,
      invalidNotes: invalidNotes,
      errors: errors,
      warnings: warnings,
      coverage: {
        eligibleCount: eligibleCount,
        minNotes: minNotes,
        maxNotes: maxNotes,
        returnedCount: returnedCount,
        status: status
      }
    };
  }

  function buildOccupiedIndex(ctx) {
    /* headings that already have an active (non-deleted) saved note */
    const idx = {};
    if (!ctx) return idx;
    const stored = loadArticleResearchNotes({ userId: ctx.userId, workspaceId: ctx.workspaceId, articleId: ctx.articleId }) || [];
    stored.forEach((n) => { if (n && n.headingId && !n.deletedAt) idx[n.headingId] = n; });
    return idx;
  }

  /* ----------------------------------------------------------------------------
     REPAIR — build payload + run exactly one repair attempt.
  ---------------------------------------------------------------------------- */
  function buildRepairPayload(ctx, originalResponse, validationResult) {
    ctx = ctx || {};
    validationResult = validationResult || { errors: [] };
    return {
      repairReason: 'validation_failed',
      articleContext: ctx.articleContext || null,
      eligibleSections: (ctx.outlineContext && ctx.outlineContext.eligibleSections) || [],
      protectedNotes: ctx.protectedNotes || [],
      rules: ctx.rules || null,
      originalResponse: originalResponse || null,
      validationErrors: (validationResult.errors || []).map((e) => ({
        noteId: e.noteId || null,
        headingId: e.headingId || null,
        issue: e.issue,
        instruction: e.instruction
      }))
    };
  }

  async function repairResearchResponseOnce({ ctx, originalResponse, validationResult, repairLLM }) {
    validationResult = validationResult || validateResearchResponse(originalResponse, ctx);

    /* already clean → just save */
    if (validationResult.valid) {
      return finishAndSave(ctx, originalResponse, validationResult);
    }

    /* no repairLLM → save what is valid, report the rest */
    if (typeof repairLLM !== 'function') {
      return finishAndSave(ctx, originalResponse, validationResult);
    }

    /* exactly one repair attempt */
    let repaired = null;
    try {
      const payload = buildRepairPayload(ctx, originalResponse, validationResult);
      repaired = await repairLLM(payload);
    } catch (e) {
      /* repair LLM failed — fall back to the original valid notes */
      return finishAndSave(ctx, originalResponse, validationResult);
    }

    const repairedValidation = validateResearchResponse(repaired || { notes: [] }, ctx);
    return finishAndSave(ctx, repaired || { notes: [] }, repairedValidation);
  }

  /* save valid notes (fill-missing) + return the summary object */
  function finishAndSave(ctx, response, validationResult) {
    const upsertRes = upsertArticleResearchNotes({
      userId: ctx.userId, workspaceId: ctx.workspaceId, articleId: ctx.articleId,
      notes: validationResult.validNotes, mode: 'fill_missing_only'
    });

    const savedCount = upsertRes.savedCount;
    const rejectedCount = (validationResult.invalidNotes || []).length + (upsertRes.skippedCount || 0);

    let status;
    if (savedCount > 0 && validationResult.errors.length === 0 && rejectedCount === 0) status = 'saved';
    else if (savedCount > 0) status = 'partial';
    else status = 'failed';

    return {
      status: status,
      savedCount: savedCount,
      rejectedCount: rejectedCount,
      errors: validationResult.errors,
      warnings: validationResult.warnings,
      coverageStatus: (response && clean(response.coverageStatus)) || validationResult.coverage.status,
      reason: (response && clean(response.reason)) || null
    };
  }

  /* ----------------------------------------------------------------------------
     STORAGE ADAPTERS — research notes kept SEPARATE from the outline.
     Swap the bodies for Supabase in the real app. Scoped by user+workspace+article.
  ---------------------------------------------------------------------------- */
  function notesStoreKey(userId, workspaceId, articleId) {
    return 'rl.articleResearchNotes.' + (userId || AUTH.userId) + '.' +
      (workspaceId || AUTH.workspaceId) + '.' + (articleId || (RA.currentArticleId && RA.currentArticleId()));
  }

  function readRecord(userId, workspaceId, articleId) {
    try {
      const raw = localStorage.getItem(notesStoreKey(userId, workspaceId, articleId));
      if (raw) return JSON.parse(raw);
    } catch (e) {}
    return null;
  }
  function writeRecord(userId, workspaceId, articleId, notes) {
    const record = {
      schemaVersion: RESEARCH_NOTE_SCHEMA_VERSION,
      userId: userId || AUTH.userId,
      workspaceId: workspaceId || AUTH.workspaceId,
      articleId: articleId || (RA.currentArticleId && RA.currentArticleId()),
      updatedAt: nowIso(),
      notes: notes
    };
    try { localStorage.setItem(notesStoreKey(userId, workspaceId, articleId), JSON.stringify(record)); } catch (e) {}
    try { console.info('[Research Agent] research notes store updated:', record.notes.length, 'notes for', record.userId, '/', record.articleId); } catch (e) {}
    return record;
  }

  function saveArticleResearchNotes({ userId, workspaceId, articleId, notes }) {
    const list = (notes || []).map((n) => applyLegacyAliases(n));
    return writeRecord(userId, workspaceId, articleId, list);
  }

  function loadArticleResearchNotes({ userId, workspaceId, articleId }) {
    const record = readRecord(userId, workspaceId, articleId);
    const notes = (record && Array.isArray(record.notes)) ? record.notes : [];
    /* active notes only (non-deleted) */
    return notes.filter((n) => n && !n.deletedAt);
  }

  function upsertArticleResearchNotes({ userId, workspaceId, articleId, notes, mode }) {
    mode = mode || 'fill_missing_only';
    const record = readRecord(userId, workspaceId, articleId);
    const existing = (record && Array.isArray(record.notes)) ? record.notes.slice() : [];

    /* index existing active notes by headingId */
    const activeByHeading = {};
    existing.forEach((n, i) => { if (n && n.headingId && !n.deletedAt) activeByHeading[n.headingId] = i; });

    let savedCount = 0, skippedCount = 0;
    (notes || []).forEach((incoming) => {
      const note = applyLegacyAliases(incoming);
      const h = note.headingId;
      const existingIdx = h != null ? activeByHeading[h] : undefined;

      if (existingIdx === undefined) {
        existing.push(note);
        activeByHeading[h] = existing.length - 1;
        savedCount++;
        return;
      }

      const cur = existing[existingIdx];
      const isProtected = cur.origin === 'manual' || (cur.origin === 'ai' && cur.editedByUser);

      if (mode === 'replace_unedited_ai' && !isProtected && cur.origin === 'ai') {
        note.updatedAt = nowIso();
        existing[existingIdx] = note;
        savedCount++;
      } else {
        /* fill_missing_only (default) — never overwrite an occupied heading */
        skippedCount++;
      }
    });

    writeRecord(userId, workspaceId, articleId, existing);
    return { savedCount: savedCount, skippedCount: skippedCount, notes: existing.filter((n) => n && !n.deletedAt) };
  }

  function softDeleteArticleResearchNote({ userId, workspaceId, articleId, headingId }) {
    const record = readRecord(userId, workspaceId, articleId);
    const existing = (record && Array.isArray(record.notes)) ? record.notes.slice() : [];
    let changed = false;
    existing.forEach((n) => {
      if (n && n.headingId === headingId && !n.deletedAt) {
        n.deletedAt = nowIso();
        n.updatedAt = nowIso();
        changed = true;
      }
    });
    if (changed) writeRecord(userId, workspaceId, articleId, existing);
    return { deleted: changed, notes: existing.filter((n) => n && !n.deletedAt) };
  }

  /* ----------------------------------------------------------------------------
     exports — augment window.ResearchAgent without removing existing functions.
  ---------------------------------------------------------------------------- */
  Object.assign(RA, {
    RESEARCH_NOTE_SCHEMA_VERSION,
    ALLOWED_RESEARCH_NOTE_TYPES,
    ALLOWED_SOURCE_RELATIONSHIPS,
    ALLOWED_COMPETITOR_RISKS,
    ALLOWED_EXAMPLE_KINDS,
    normalizeResearchNote,
    validateResearchNote,
    validateResearchResponse,
    coverageBudget,
    buildRepairPayload,
    repairResearchResponseOnce,
    saveArticleResearchNotes,
    loadArticleResearchNotes,
    upsertArticleResearchNotes,
    softDeleteArticleResearchNote
  });
})();
