import {
  loadMemory
} from "./chunk-DFR4DJBM.js";
import {
  LUMENFLOW_MEMORY_PATHS
} from "./chunk-4N74J3UT.js";

// ../memory/dist/mem-export-core.js
import path from "path";
function applyFilters(nodes, options) {
  const { wuId, type, lifecycle } = options;
  return nodes.filter((node) => {
    if (wuId && node.wu_id !== wuId)
      return false;
    if (type && node.type !== type)
      return false;
    if (lifecycle && node.lifecycle !== lifecycle)
      return false;
    return true;
  });
}
function formatFilters(options) {
  const parts = [];
  if (options.wuId)
    parts.push(`wu=${options.wuId}`);
  if (options.type)
    parts.push(`type=${options.type}`);
  if (options.lifecycle)
    parts.push(`lifecycle=${options.lifecycle}`);
  return parts.length === 0 ? "none" : parts.join(", ");
}
function formatMarkdown(nodes, options) {
  const lines = [];
  lines.push("# Memory Export");
  lines.push(`Filters: ${formatFilters(options)}`);
  lines.push(`Total: ${nodes.length}`);
  lines.push("");
  if (nodes.length === 0) {
    lines.push("No matching nodes.");
    return lines.join("\n");
  }
  for (const node of nodes) {
    lines.push(`## ${node.id} (${node.type})`);
    lines.push(`- Created: ${node.created_at}`);
    lines.push(`- Lifecycle: ${node.lifecycle}`);
    if (node.wu_id) {
      lines.push(`- WU: ${node.wu_id}`);
    }
    lines.push(`- Content: ${node.content}`);
    if (node.tags && node.tags.length > 0) {
      lines.push(`- Tags: ${node.tags.join(", ")}`);
    }
    if (node.metadata && Object.keys(node.metadata).length > 0) {
      lines.push(`- Metadata: ${JSON.stringify(node.metadata)}`);
    }
    lines.push("");
  }
  return lines.join("\n");
}
function formatJson(nodes, options) {
  const payload = {
    count: nodes.length,
    filters: {
      wuId: options.wuId ?? null,
      type: options.type ?? null,
      lifecycle: options.lifecycle ?? null
    },
    nodes
  };
  return JSON.stringify(payload, null, 2);
}
async function exportMemory(baseDir, options = {}) {
  const memoryDir = path.join(baseDir, LUMENFLOW_MEMORY_PATHS.MEMORY_DIR);
  const memory = await loadMemory(memoryDir);
  const nodes = applyFilters(memory.nodes, options);
  const format = options.format ?? "markdown";
  const output = format === "json" ? formatJson(nodes, options) : formatMarkdown(nodes, options);
  return {
    format,
    nodes,
    output
  };
}

export {
  exportMemory
};
