/**
 * Knowledge-graph safety guards.
 *
 * The "Full Analysis" pass lets the LLM propose `merges` (collapse two topics
 * into one) and `deletions` (drop a topic entirely). Both are destructive and
 * persisted via bulkSave → db.saveTopics, which wipes-and-rewrites the
 * `topics` collection.
 *
 * Two classes of topic must NEVER be removed by an AI suggestion:
 *
 *   1. `learning_relevance === 'exclude'`
 *        Reference material — kept on purpose, surfaced only to R42 search,
 *        intentionally excluded from theme topics. An admin made this choice;
 *        the AI's "irrelevant" judgement must not override it.
 *
 *   2. `relevance_locked === true`
 *        Admin pinned this row's relevance. By extension the row itself is
 *        also pinned — deleting it would be a louder change than re-scoring it.
 *
 * `filterAiActions` strips any merge/deletion that would touch a protected id
 * BEFORE it reaches bulkSave. The model still gets to suggest them (we can't
 * stop it generating), but those suggestions are dropped client-side.
 *
 * The function is intentionally pure so it is trivially unit-testable.
 */

/**
 * @param {{ learning_relevance?: string, relevance_locked?: boolean }} topic
 */
export function isProtectedTopic(topic) {
  if (!topic) return false;
  if (topic.learning_relevance === 'exclude') return true;
  if (topic.relevance_locked === true) return true;
  return false;
}

/**
 * Strip protected topics out of `actions.deletions` and `actions.merges`.
 *
 * Merges have two ids:
 *   - `keepId`    — the survivor
 *   - `deleteId`  — gets removed and its relations re-pointed
 *
 * If `deleteId` is protected we drop the entire merge (we will not delete a
 * protected topic, even to consolidate it). If `keepId` is protected we keep
 * the merge — folding others into a protected canonical topic is fine.
 *
 * @param {object[]} currentTopics
 * @param {{ merges?: {keepId: string, deleteId: string}[], deletions?: string[], newRelations?: object[], relevanceUpdates?: object[] }} actions
 * @returns {{ filtered: object, dropped: { deletions: string[], merges: object[] } }}
 */
export function filterAiActions(currentTopics, actions) {
  const byId = new Map(currentTopics.map(t => [t.id, t]));
  const isProtected = (id) => isProtectedTopic(byId.get(id));

  const droppedDeletions = [];
  const keptDeletions = [];
  for (const id of actions?.deletions ?? []) {
    if (isProtected(id)) droppedDeletions.push(id);
    else keptDeletions.push(id);
  }

  const droppedMerges = [];
  const keptMerges = [];
  for (const m of actions?.merges ?? []) {
    if (isProtected(m?.deleteId)) droppedMerges.push(m);
    else keptMerges.push(m);
  }

  return {
    filtered: {
      ...(actions || {}),
      deletions: keptDeletions,
      merges: keptMerges,
    },
    dropped: {
      deletions: droppedDeletions,
      merges: droppedMerges,
    },
  };
}
