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

// ../memory/dist/mem-ready-core.js
import fs from "fs/promises";
import path from "path";
var RELATIONSHIPS_FILE_NAME = "relationships.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);
}
async function loadRelationships(memoryDir) {
  const filePath = path.join(memoryDir, RELATIONSHIPS_FILE_NAME);
  try {
    const content = await fs.readFile(filePath, { encoding: "utf-8" });
    const lines = content.split("\n");
    const relationships = [];
    for (const line of lines) {
      const trimmed = line.trim();
      if (!trimmed)
        continue;
      try {
        relationships.push(JSON.parse(trimmed));
      } catch {
        continue;
      }
    }
    return relationships;
  } catch (err) {
    const error = err;
    if (error.code === "ENOENT") {
      return [];
    }
    throw error;
  }
}
function buildBlockedSet(relationships) {
  const blocked = /* @__PURE__ */ new Set();
  for (const rel of relationships) {
    if (rel.type === "blocks") {
      blocked.add(rel.to_id);
    }
  }
  return blocked;
}
function isBlocked(node, blockedByRelationships) {
  if (blockedByRelationships.has(node.id)) {
    return true;
  }
  const blockedBy = node.metadata?.blocked_by;
  if (Array.isArray(blockedBy) && blockedBy.length > 0) {
    return true;
  }
  return false;
}
function isClosed(node) {
  if (node.lifecycle === "ephemeral") {
    return true;
  }
  if (node.metadata?.status === "closed") {
    return true;
  }
  return false;
}
function validateWuId(wuId) {
  if (!MEMORY_PATTERNS.WU_ID.test(wuId)) {
    throw createError(ErrorCodes.INVALID_WU_ID, `Invalid WU ID format: ${wuId}. Expected format: WU-XXX (e.g., WU-1234)`);
  }
}
async function queryReadyNodes(baseDir, options) {
  const { wuId, type } = options;
  validateWuId(wuId);
  const memoryDir = path.join(baseDir, LUMENFLOW_MEMORY_PATHS.MEMORY_DIR);
  const memory = await loadMemory(memoryDir);
  const relationships = await loadRelationships(memoryDir);
  const blockedByRelationships = buildBlockedSet(relationships);
  const wuNodes = memory.byWu.get(wuId) ?? [];
  const readyNodes = wuNodes.filter((node) => {
    if (isBlocked(node, blockedByRelationships)) {
      return false;
    }
    if (isClosed(node)) {
      return false;
    }
    if (type && node.type !== type) {
      return false;
    }
    return true;
  });
  return readyNodes.sort(compareNodes);
}

export {
  queryReadyNodes
};
