#!/usr/bin/env node
/**
 * Parse Slack MCP search results from stdin and ingest into WALL-E brain.
 * Designed to be piped: slack search output | node ingest-slack-search.js
 *
 * Usage:
 *   echo "$RESULTS" | node scripts/ingest-slack-search.js
 *   node scripts/ingest-slack-search.js < /tmp/results.txt
 */
'use strict';
const brain = require('../brain');
brain.initDb();

const OWNER_ID = process.env.SLACK_OWNER_USER_ID;
if (!OWNER_ID) throw new Error('SLACK_OWNER_USER_ID env var required');
const input = require('fs').readFileSync('/dev/stdin', 'utf8');

// Parse the MCP search result format
const blocks = input.split(/^---$/m).filter(b => b.trim());
let ingested = 0, skipped = 0;

for (const block of blocks) {
  const lines = block.split('\n');
  let channelId = '', channel = '', sender = '', senderId = '', ts = '', text = '', participants = [];

  for (let i = 0; i < lines.length; i++) {
    const l = lines[i].trim();
    if (l.startsWith('Channel:')) {
      const m = l.match(/\(ID:\s*(\S+)\)/);
      if (m) channelId = m[1];
      channel = l.replace(/Channel:\s*/, '').replace(/\s*\(ID:.*/, '').trim();
    }
    if (l.startsWith('Participants:')) {
      const pMatches = [...l.matchAll(/([A-Za-z][\w\s.'-]+?)\s*\(ID:/g)];
      participants = pMatches.map(m => m[1].trim());
    }
    if (l.startsWith('From:')) {
      const m = l.match(/From:\s*(.*?)\s*\(ID:\s*(\S+)\)/);
      if (m) { sender = m[1].trim(); senderId = m[2]; }
    }
    if (l.startsWith('Message_ts:')) ts = l.replace('Message_ts:', '').trim();
    if (l.startsWith('Text:')) {
      // Collect text from next lines until Context or end
      const textLines = [];
      for (let j = i + 1; j < lines.length; j++) {
        if (lines[j].trim().startsWith('Context') || lines[j].trim().startsWith('Reply count')) break;
        textLines.push(lines[j]);
      }
      text = textLines.join('\n').trim();
      break;
    }
  }

  if (!text || text.length < 3 || !ts) { skipped++; continue; }

  const isOwner = senderId === OWNER_ID;
  const timestamp = new Date(parseFloat(ts) * 1000).toISOString();

  // Resolve DM/Group DM channel names using participants
  if ((channel === 'DM' || channel === 'Group DM' || !channel) && participants.length > 0) {
    const ownerFirst = (process.env.WALLE_OWNER_NAME || '').split(' ')[0].toLowerCase();
    const others = participants
      .filter(p => !ownerFirst || !p.toLowerCase().startsWith(ownerFirst))
      .map(p => p.split(' ')[0])
      .slice(0, 3);
    if (others.length > 0) channel = `DM with ${others.join(', ')}`;
  }

  const result = brain.insertMemory({
    source: 'slack',
    source_id: `slack-${channelId}-${ts}`,
    source_channel: channel || channelId,
    memory_type: isOwner ? 'message_sent' : 'message_received',
    direction: isOwner ? 'outbound' : 'inbound',
    participants: JSON.stringify(participants.length > 0 ? participants : [sender]),
    content: `${sender}: ${text}`,
    timestamp,
    metadata: JSON.stringify({ source: 'slack_search_import' }),
  });
  if (result) ingested++;
  else skipped++;
}

console.log(`+${ingested} new | ${skipped} skipped | total: ${brain.getBrainStats().memory_count}`);
brain.closeDb();
