'use strict';

/**
 * Noise stripper: removes Claude Code/Slack UI chrome from ingested content.
 * Applied at ingestion time so search, extraction, and context all work on clean text.
 * Ported from MemPalace normalize.py strip_noise.
 */

// XML-like tags from Claude Code system (line-anchored, won't cross blank lines)
const NOISE_TAGS = [
  'system-reminder', 'command-message', 'command-name', 'command-args',
  'task-notification', 'user-prompt-submit-hook', 'hook_output',
  'available-deferred-tools', 'fast_mode_info',
];

// Build tag-stripping regex: matches <tag ...>content</tag> but won't cross double-newlines
const TAG_PATTERNS = NOISE_TAGS.map(tag =>
  new RegExp(`(?:^|\\n)(?:> )?<${tag}(?:\\s[^>]*)?>(?:(?!\\n\\s*\\n)[\\s\\S])*?</${tag}>[ \\t]*\\n?`, 'gm')
);

// Line-anchored noise prefixes
const LINE_NOISE_PATTERNS = [
  /^(?:> )?CURRENT TIME:.*\n?/gm,
  /^(?:> )?VERIFIED FACTS \(do not contradict\).*\n?/gm,
  /^(?:> )?AGENT SPECIALIZATION:.*\n?/gm,
  /^(?:> )?Checking\.{2,}.*\n?/gm,
  /^(?:> )?Ran \d+ (?:Stop|PreCompact|PreToolUse|SessionStart|PostToolUse) hooks?.*\n?/gm,
  /^(?:> )?… \+\d+ lines?\n?/gm,
  /\s*\[\d+\s+tokens?\]\s*\(ctrl\+o to expand\)/g,
];

// Collapse excessive blank lines (max 2 consecutive newlines)
const EXCESSIVE_BLANKS = /\n{4,}/g;

/**
 * Strip noise from content.
 * @param {string} content - Raw memory content
 * @returns {string} Cleaned content
 */
function stripNoise(content) {
  if (!content || typeof content !== 'string') return content || '';

  let cleaned = content;

  // Strip noise tags
  for (const pattern of TAG_PATTERNS) {
    pattern.lastIndex = 0;
    cleaned = cleaned.replace(pattern, '\n');
  }

  // Strip line-anchored noise
  for (const pattern of LINE_NOISE_PATTERNS) {
    pattern.lastIndex = 0;
    cleaned = cleaned.replace(pattern, '');
  }

  // Collapse excessive blank lines
  cleaned = cleaned.replace(EXCESSIVE_BLANKS, '\n\n\n');

  return cleaned.trim();
}

module.exports = { stripNoise, NOISE_TAGS };
