import {
  ErrorCodes,
  createError
} from "./chunk-RXRKBBSM.js";

// ../memory/dist/memory-store.js
import fs from "fs/promises";
import path from "path";

// ../memory/dist/memory-schema.js
import { z } from "zod";
var MEMORY_NODE_TYPES = ["session", "discovery", "checkpoint", "note", "summary"];
var MEMORY_LIFECYCLES = ["ephemeral", "session", "wu", "project"];
var RELATIONSHIP_TYPES = ["blocks", "parent_child", "related", "discovered_from"];
var MEMORY_PATTERNS = {
  /** Memory ID format: mem-[a-z0-9]{4} */
  MEMORY_ID: /^mem-[a-z0-9]{4}$/,
  /** WU ID format (reused from wu-schema) */
  WU_ID: /^WU-\d+$/
};
var ERROR_MESSAGES = {
  MEMORY_ID: "ID must match pattern mem-[a-z0-9]{4} (e.g., mem-abc1)",
  NODE_TYPE: `Type must be one of: ${MEMORY_NODE_TYPES.join(", ")}`,
  LIFECYCLE: `Lifecycle must be one of: ${MEMORY_LIFECYCLES.join(", ")}`,
  RELATIONSHIP_TYPE: `Type must be one of: ${RELATIONSHIP_TYPES.join(", ")}`,
  WU_ID: "WU ID must match pattern WU-XXX (e.g., WU-1462)",
  CONTENT_REQUIRED: "Content is required",
  DATETIME_REQUIRED: "Created timestamp is required"
};
var MemoryNodeSchema = z.object({
  /** Memory node identifier (mem-[a-z0-9]{4}) */
  id: z.string().regex(MEMORY_PATTERNS.MEMORY_ID, { message: ERROR_MESSAGES.MEMORY_ID }),
  /** Node type classification */
  type: z.enum(MEMORY_NODE_TYPES, {
    error: ERROR_MESSAGES.NODE_TYPE
  }),
  /** Lifecycle duration */
  lifecycle: z.enum(MEMORY_LIFECYCLES, {
    error: ERROR_MESSAGES.LIFECYCLE
  }),
  /** Node content (required, non-empty) */
  content: z.string().min(1, { message: ERROR_MESSAGES.CONTENT_REQUIRED }),
  /** Creation timestamp (ISO 8601 datetime) */
  created_at: z.string().datetime({ message: ERROR_MESSAGES.DATETIME_REQUIRED }),
  /** Last update timestamp (optional, ISO 8601 datetime) */
  updated_at: z.string().datetime().optional(),
  /** Associated WU ID (optional) */
  wu_id: z.string().regex(MEMORY_PATTERNS.WU_ID, { message: ERROR_MESSAGES.WU_ID }).optional(),
  /** Session ID this node belongs to (optional, UUID) */
  session_id: z.string().uuid().optional(),
  /** Arbitrary metadata (optional) */
  metadata: z.record(z.string(), z.unknown()).optional(),
  /** Tags for categorization (optional) */
  tags: z.array(z.string()).optional()
});
var RelationshipSchema = z.object({
  /** Source node ID (mem-[a-z0-9]{4}) */
  from_id: z.string().regex(MEMORY_PATTERNS.MEMORY_ID, { message: ERROR_MESSAGES.MEMORY_ID }),
  /** Target node ID (mem-[a-z0-9]{4}) */
  to_id: z.string().regex(MEMORY_PATTERNS.MEMORY_ID, { message: ERROR_MESSAGES.MEMORY_ID }),
  /** Relationship type */
  type: z.enum(RELATIONSHIP_TYPES, {
    error: ERROR_MESSAGES.RELATIONSHIP_TYPE
  }),
  /** Creation timestamp (optional, ISO 8601 datetime) */
  created_at: z.string().datetime().optional(),
  /** Arbitrary metadata (optional) */
  metadata: z.record(z.string(), z.unknown()).optional()
});
function validateMemoryNode(data) {
  return MemoryNodeSchema.safeParse(data);
}
function validateRelationship(data) {
  return RelationshipSchema.safeParse(data);
}

// ../memory/dist/memory-store.js
var MEMORY_FILE_NAME = "memory.jsonl";
var PRIORITY_RANK = {
  P0: 0,
  P1: 1,
  P2: 2,
  P3: 3
};
var DEFAULT_PRIORITY_RANK = 999;
function getPriorityRank(node) {
  const priority = node.metadata?.priority;
  if (!priority) {
    return DEFAULT_PRIORITY_RANK;
  }
  return PRIORITY_RANK[priority] ?? DEFAULT_PRIORITY_RANK;
}
function compareNodes(a, b) {
  const priorityDiff = getPriorityRank(a) - getPriorityRank(b);
  if (priorityDiff !== 0) {
    return priorityDiff;
  }
  const aTime = new Date(a.created_at).getTime();
  const bTime = new Date(b.created_at).getTime();
  if (aTime !== bTime) {
    return aTime - bTime;
  }
  return a.id.localeCompare(b.id);
}
function isNodeArchived(node) {
  return node.metadata?.status === "archived";
}
async function loadMemory(baseDir, options = {}) {
  const { includeArchived = false } = options;
  const filePath = path.join(baseDir, MEMORY_FILE_NAME);
  const content = await readMemoryFileOrEmpty(filePath);
  if (content === null) {
    return createEmptyIndexedMemory();
  }
  return parseAndIndexMemory(content, includeArchived);
}
async function readMemoryFileOrEmpty(filePath) {
  try {
    return await fs.readFile(filePath, { encoding: "utf-8" });
  } catch (err) {
    const error = err;
    if (error.code === "ENOENT") {
      return null;
    }
    throw error;
  }
}
function createEmptyIndexedMemory() {
  return {
    nodes: [],
    byId: /* @__PURE__ */ new Map(),
    byWu: /* @__PURE__ */ new Map()
  };
}
function parseAndValidateLine(line, lineNumber) {
  let parsed;
  try {
    parsed = JSON.parse(line);
  } catch (err) {
    const errMsg = err instanceof Error ? err.message : String(err);
    throw createError(ErrorCodes.PARSE_ERROR, `Malformed JSON on line ${lineNumber}: ${errMsg}`, {
      cause: err
    });
  }
  const validation = validateMemoryNode(parsed);
  if (!validation.success) {
    const issues = validation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ");
    throw createError(ErrorCodes.VALIDATION_ERROR, `Validation error on line ${lineNumber}: ${issues}`);
  }
  return validation.data;
}
function indexNodeByWu(result, node) {
  if (!node.wu_id)
    return;
  if (!result.byWu.has(node.wu_id)) {
    result.byWu.set(node.wu_id, []);
  }
  const wuNodes = result.byWu.get(node.wu_id);
  if (wuNodes) {
    wuNodes.push(node);
  }
}
function parseAndIndexMemory(content, includeArchived) {
  const result = createEmptyIndexedMemory();
  const lines = content.split("\n");
  const allParsed = [];
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i]?.trim() ?? "";
    if (!line)
      continue;
    const node = parseAndValidateLine(line, i + 1);
    allParsed.push(node);
    result.byId.set(node.id, node);
  }
  const seen = /* @__PURE__ */ new Set();
  for (const node of allParsed) {
    if (seen.has(node.id))
      continue;
    const latestVersion = result.byId.get(node.id);
    if (!latestVersion)
      continue;
    seen.add(node.id);
    if (!includeArchived && isNodeArchived(latestVersion)) {
      result.byId.delete(node.id);
      continue;
    }
    result.nodes.push(latestVersion);
    result.byId.set(node.id, latestVersion);
    indexNodeByWu(result, latestVersion);
  }
  return result;
}
async function loadMemoryAll(baseDir) {
  return loadMemory(baseDir, { includeArchived: true });
}
async function appendNode(baseDir, node) {
  const validation = validateMemoryNode(node);
  if (!validation.success) {
    const issues = validation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ");
    throw createError(ErrorCodes.VALIDATION_ERROR, `Validation error: ${issues}`);
  }
  const filePath = path.join(baseDir, MEMORY_FILE_NAME);
  const line = JSON.stringify(node) + "\n";
  await fs.appendFile(filePath, line, { encoding: "utf-8" });
  return node;
}
async function queryReady(baseDir, wuId, options = {}) {
  const { includeArchived = false } = options;
  const memory = await loadMemory(baseDir, { includeArchived });
  const wuNodes = memory.byWu.get(wuId) ?? [];
  return [...wuNodes].sort(compareNodes);
}
async function queryByWu(baseDir, wuId, options = {}) {
  const { includeArchived = false } = options;
  const memory = await loadMemory(baseDir, { includeArchived });
  return memory.byWu.get(wuId) ?? [];
}

export {
  MEMORY_NODE_TYPES,
  MEMORY_PATTERNS,
  validateMemoryNode,
  validateRelationship,
  MEMORY_FILE_NAME,
  loadMemory,
  loadMemoryAll,
  appendNode,
  queryReady,
  queryByWu
};
