'use strict';

/**
 * Claude.ai web export adapter.
 * Parses JSON exports from claude.ai (Settings > Export Data).
 * Usage: Place export JSON files in ~/.walle/imports/claude-web/
 */

const fs = require('fs');
const path = require('path');

const IMPORT_DIR = path.join(process.env.HOME, '.walle', 'imports', 'claude-web');

function poll(since) {
  const memories = [];
  if (!fs.existsSync(IMPORT_DIR)) return memories;

  const files = fs.readdirSync(IMPORT_DIR).filter(f => f.endsWith('.json'));
  for (const file of files) {
    try {
      const data = JSON.parse(fs.readFileSync(path.join(IMPORT_DIR, file), 'utf8'));

      // Claude.ai export can be flat array or nested with conversations key
      const conversations = Array.isArray(data) ? data : (data.conversations || data.chats || []);

      for (const conv of conversations) {
        const messages = conv.chat_messages || conv.messages || [];
        const title = conv.name || conv.title || 'Untitled';
        const convId = conv.uuid || conv.id || file;

        // Pair user + assistant messages by scanning roles (not assuming strict alternation)
        let i = 0;
        while (i < messages.length) {
          const msg = messages[i];
          const role = typeof msg === 'string' ? 'user' : (msg.role || msg.sender || 'user');
          if (role !== 'human' && role !== 'user') { i++; continue; }
          const userMsg = msg;
          i++;
          // Find next assistant message
          let assistantMsg = null;
          if (i < messages.length) {
            const nextMsg = messages[i];
            const nextRole = typeof nextMsg === 'string' ? 'assistant' : (nextMsg.role || nextMsg.sender || '');
            if (nextRole === 'assistant') { assistantMsg = nextMsg; i++; }
          }

          const timestamp = (typeof userMsg === 'object' ? (userMsg.created_at || userMsg.timestamp) : null) || conv.created_at;
          if (since && timestamp && timestamp <= since) continue;

          const userText = typeof userMsg === 'string' ? userMsg :
            (userMsg.text || userMsg.content || '');
          const assistantText = assistantMsg ?
            (typeof assistantMsg === 'string' ? assistantMsg :
              (assistantMsg.text || assistantMsg.content || '')) : '';

          let content = `> ${userText}`;
          if (assistantText) content += `\n\n${assistantText}`;

          memories.push({
            source: 'claude-web',
            source_id: `claude-web-${convId}-${memories.length}`,
            content: content.slice(0, 10000),
            timestamp: timestamp || new Date().toISOString(),
            metadata: JSON.stringify({ title, file }),
          });
        }
      }
    } catch (err) {
      console.error(`[claude-web-adapter] Failed to parse ${file}:`, err.message);
    }
  }
  return memories;
}

module.exports = { poll };
