import { getMsgCache } from './data.js';
import { stripTags, showToast } from './utils.js';
import { getCurrentSessionId } from './sessions.js';

export function toggleExportMenu() {
  const menu = document.getElementById('export-menu');
  menu.classList.toggle('hidden');
  if (!menu.classList.contains('hidden')) {
    setTimeout(() => {
      document.addEventListener('click', closeExportMenu, { once: true });
    }, 0);
  }
}

function closeExportMenu(e) {
  const menu = document.getElementById('export-menu');
  if (menu && !document.getElementById('export-wrap')?.contains(e?.target)) {
    menu.classList.add('hidden');
  }
}

export function exportSession(mode, filter) {
  document.getElementById('export-menu').classList.add('hidden');
  const currentSessionId = getCurrentSessionId();
  const msgCache = getMsgCache();
  if (!currentSessionId || !msgCache[currentSessionId]) return;

  const msgs = msgCache[currentSessionId];
  const typeSet = filter === 'user' ? new Set(['user'])
    : filter === 'assistant' ? new Set(['assistant'])
    : filter === 'conversation' ? new Set(['user', 'assistant'])
    : null;

  const filtered = typeSet ? msgs.filter(m => typeSet.has(m.type)) : msgs;

  if (mode === 'clipboard') {
    const text = filtered.map(m => {
      let line = `[${m.timestamp.slice(0, 19)}] [${m.type.toUpperCase()}]`;
      if (m.tool) line += ` [${m.tool.tool_name}]`;
      if (m.result) line += ` [${m.result.status}]`;
      line += '\n';
      if (m.content) line += stripTags(m.content);
      if (m.tool && m.tool.tool_input) line += '\n--- tool input ---\n' + m.tool.tool_input;
      if (m.result && m.result.output) line += '\n--- output ---\n' + m.result.output;
      return line;
    }).join('\n\n---\n\n');
    navigator.clipboard.writeText(text).then(() => showToast(`Copied ${filtered.length} messages`));
  } else {
    const json = JSON.stringify({
      session_id: currentSessionId,
      filter,
      message_count: filtered.length,
      messages: filtered,
    }, null, 2);
    const blob = new Blob([json], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `session_${currentSessionId.slice(0, 8)}_${filter}.json`;
    a.click();
    URL.revokeObjectURL(url);
    showToast(`Downloaded ${filtered.length} messages`);
  }
}
