import {
  generateMemId
} from "./chunk-RIAAGL2E.js";
import {
  appendNode,
  loadMemory,
  validateMemoryNode
} from "./chunk-DFR4DJBM.js";
import {
  LUMENFLOW_MEMORY_PATHS
} from "./chunk-4N74J3UT.js";
import {
  ErrorCodes,
  createError
} from "./chunk-RXRKBBSM.js";

// ../memory/dist/mem-summarize-core.js
import path from "path";
var SUMMARIZABLE_TYPES = ["discovery", "checkpoint", "note", "session"];
var PROTECTED_LIFECYCLES = ["project"];
function filterSummarizableNodes(nodes, wuId) {
  return nodes.filter((node) => {
    if (node.wu_id !== wuId) {
      return false;
    }
    if (node.lifecycle === "ephemeral") {
      return false;
    }
    if (node.metadata?.summarized_into) {
      return false;
    }
    if (node.type === "summary") {
      return false;
    }
    return SUMMARIZABLE_TYPES.includes(node.type);
  });
}
function getCompactionRatio(sourceCount, summaryCount) {
  if (sourceCount === 0 || summaryCount === 0) {
    return 0;
  }
  return sourceCount / summaryCount;
}
function groupNodesByType(nodes) {
  const groups = /* @__PURE__ */ new Map();
  for (const node of nodes) {
    if (!groups.has(node.type)) {
      groups.set(node.type, []);
    }
    const typeGroup = groups.get(node.type);
    if (typeGroup) {
      typeGroup.push(node);
    }
  }
  return groups;
}
function generateSummaryContent(nodes, wuId) {
  const groups = groupNodesByType(nodes);
  const sections = [];
  sections.push(`# Summary for ${wuId}`);
  sections.push(`Aggregated from ${nodes.length} node(s)`);
  const typeOrder = ["discovery", "checkpoint", "note", "session"];
  for (const type of typeOrder) {
    const typeNodes = groups.get(type);
    if (!typeNodes || typeNodes.length === 0) {
      continue;
    }
    sections.push(`## ${type.charAt(0).toUpperCase() + type.slice(1)}(s)`);
    for (const node of typeNodes) {
      const content = node.content.length > 200 ? `${node.content.slice(0, 197)}...` : node.content;
      sections.push(`- ${content}`);
    }
  }
  return sections.join("\n");
}
function filterNodesForCleanup(nodes) {
  return nodes.filter((node) => !PROTECTED_LIFECYCLES.includes(node.lifecycle));
}
function createSummaryNode(sourceNodes, wuId) {
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
  const content = generateSummaryContent(sourceNodes, wuId);
  const id = generateMemId(`summary-${wuId}-${timestamp}`);
  const summary = {
    id,
    type: "summary",
    lifecycle: "project",
    // Summaries persist across WUs
    content,
    created_at: timestamp,
    wu_id: wuId,
    metadata: {
      source_nodes: sourceNodes.map((n) => n.id),
      source_count: sourceNodes.length,
      summarized_at: timestamp
    }
  };
  const validation = validateMemoryNode(summary);
  if (!validation.success) {
    const issues = validation.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join(", ");
    throw createError(ErrorCodes.VALIDATION_ERROR, `Summary node validation failed: ${issues}`);
  }
  return summary;
}
function createCleanupMarkers(nodes, summaryId) {
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
  return nodes.map((node) => ({
    ...node,
    updated_at: timestamp,
    metadata: {
      ...node.metadata,
      summarized_into: summaryId,
      summarized_at: timestamp
    }
  }));
}
async function summarizeWu(baseDir, options) {
  const { wuId, dryRun = false } = options;
  const memoryDir = path.join(baseDir, LUMENFLOW_MEMORY_PATHS.MEMORY_DIR);
  const memory = await loadMemory(memoryDir);
  const summarizable = filterSummarizableNodes(memory.nodes, wuId);
  if (summarizable.length === 0) {
    throw createError(ErrorCodes.NODE_NOT_FOUND, `No summarizable nodes found for ${wuId}`);
  }
  const summary = createSummaryNode(summarizable, wuId);
  const cleanupNodes = filterNodesForCleanup(summarizable);
  const markedForCleanup = cleanupNodes.map((n) => n.id);
  const compactionRatio = getCompactionRatio(summarizable.length, 1);
  if (dryRun) {
    return {
      success: true,
      summary,
      markedForCleanup,
      dryRun: true,
      compactionRatio
    };
  }
  await appendNode(memoryDir, summary);
  const cleanupMarkers = createCleanupMarkers(cleanupNodes, summary.id);
  for (const marker of cleanupMarkers) {
    await appendNode(memoryDir, marker);
  }
  return {
    success: true,
    summary,
    markedForCleanup,
    compactionRatio
  };
}

export {
  summarizeWu
};
