#!/usr/bin/env node
/**
 * Pull Slack history into WALL-E brain by parsing search results.
 * This script is meant to be run manually — it reads pre-fetched search results
 * from stdin or a file and ingests them into the brain.
 *
 * Usage:
 *   node scripts/pull-slack-via-claude.js < /tmp/slack-results.txt
 *   node scripts/pull-slack-via-claude.js /tmp/slack-results.txt
 */
'use strict';
const fs = require('fs');
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 OWNER_NAME = process.env.WALLE_OWNER_NAME || 'Owner';

function parseSearchResults(text) {
  const messages = [];
  const blocks = text.split('---').filter(b => b.trim());

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

    for (const line of lines) {
      const l = line.trim();
      if (l.startsWith('Channel:')) {
        const m = l.match(/Channel:\s*(.*?)\s*\(ID:\s*(.*?)\)/);
        if (m) { channel = m[1].trim(); channelId = m[2]; }
      }
      if (l.startsWith('From:')) {
        const m = l.match(/From:\s*(.*?)\s*\(ID:\s*(.*?)\)/);
        if (m) { sender = m[1].trim(); senderId = m[2]; }
      }
      if (l.startsWith('Time:')) {
        ts = l.replace('Time:', '').trim();
      }
      if (l.startsWith('Message_ts:')) {
        msgTs = l.replace('Message_ts:', '').trim();
      }
      if (l.startsWith('Text:')) {
        msgText = lines.slice(lines.indexOf(line) + 1).join('\n').split('Context')[0].trim();
        break;
      }
      if (l.startsWith('Participants:')) {
        const pMatch = l.matchAll(/(\w[\w\s]+?)\s*\(ID:/g);
        for (const pm of pMatch) participants.push(pm[1].trim());
      }
    }

    if (!msgText || !msgTs) continue;

    const isOwner = senderId === OWNER_ID;
    const timestamp = ts ? new Date(ts + ' UTC').toISOString() : new Date(parseFloat(msgTs) * 1000).toISOString();

    messages.push({
      source_id: `slack-${channelId}-${msgTs}`,
      channel: channel || channelId,
      sender: sender || (isOwner ? OWNER_NAME : 'unknown'),
      is_owner: isOwner,
      text: msgText,
      timestamp,
      participants: participants.length > 0 ? participants : [sender || 'unknown'],
    });
  }

  return messages;
}

// Read input
const inputFile = process.argv[2] || '/dev/stdin';
const text = fs.readFileSync(inputFile, 'utf8');
const messages = parseSearchResults(text);

let ingested = 0;
for (const m of messages) {
  const result = brain.insertMemory({
    source: 'slack',
    source_id: m.source_id,
    source_channel: m.channel,
    memory_type: m.is_owner ? 'message_sent' : 'message_received',
    direction: m.is_owner ? 'outbound' : 'inbound',
    participants: JSON.stringify(m.participants),
    content: m.sender + ': ' + m.text,
    timestamp: m.timestamp,
    metadata: JSON.stringify({ source: 'slack_import' }),
  });
  if (result) ingested++;
}

console.log(`Parsed: ${messages.length} messages, Ingested: ${ingested} new`);
console.log(`Total memories: ${brain.getBrainStats().memory_count}`);
brain.closeDb();
