import {
  ensureMemoryDir
} from "./chunk-ND6MY37M.js";
import {
  generateMemId
} from "./chunk-RIAAGL2E.js";
import {
  MEMORY_NODE_TYPES,
  MEMORY_PATTERNS,
  appendNode,
  validateMemoryNode,
  validateRelationship
} from "./chunk-DFR4DJBM.js";
import {
  LUMENFLOW_MEMORY_PATHS
} from "./chunk-4N74J3UT.js";
import {
  GIT_DIRECTORY_NAME,
  GIT_WORKTREES_SENTINEL
} from "./chunk-V6OJGLBA.js";
import {
  ErrorCodes,
  createError
} from "./chunk-RXRKBBSM.js";

// ../memory/dist/mem-create-core.js
import fs from "fs/promises";
import path from "path";
var RELATIONSHIPS_FILE_NAME = "relationships.jsonl";
var DEFAULT_NODE_TYPE = "discovery";
var TYPE_ALIASES = {
  bug: { type: "discovery", tag: "bug" },
  idea: { type: "discovery", tag: "idea" },
  question: { type: "discovery", tag: "question" },
  dependency: { type: "discovery", tag: "dependency" }
};
var LIFECYCLE_BY_TYPE = {
  session: "wu",
  discovery: "wu",
  checkpoint: "session",
  note: "session",
  summary: "project"
};
var ERROR_MESSAGES = {
  TITLE_REQUIRED: "title is required",
  TITLE_EMPTY: "title cannot be empty",
  INVALID_TYPE: `Invalid node type. Must be one of: ${MEMORY_NODE_TYPES.join(", ")}`,
  WU_ID_INVALID: "Invalid WU ID format. Expected pattern: WU-XXX (e.g., WU-123)",
  MEMORY_ID_INVALID: "Invalid memory ID format. Expected pattern: mem-XXXX (e.g., mem-a1b2)"
};
function normalizeType(inputType) {
  const alias = TYPE_ALIASES[inputType];
  if (alias) {
    return { type: alias.type, aliasTag: alias.tag };
  }
  return { type: inputType, aliasTag: null };
}
async function getMainCheckoutFromWorktree(dir) {
  const gitPath = path.join(dir, GIT_DIRECTORY_NAME);
  try {
    const stat = await fs.stat(gitPath);
    if (stat.isFile()) {
      const gitContent = await fs.readFile(gitPath, { encoding: "utf-8" });
      const match = gitContent.match(/^gitdir:\s*(.+)/);
      if (match && match[1]) {
        const gitDir = match[1].trim();
        const worktreesIndex = gitDir.indexOf(GIT_WORKTREES_SENTINEL);
        if (worktreesIndex !== -1) {
          return gitDir.substring(0, worktreesIndex);
        }
      }
    }
  } catch {
  }
  return null;
}
async function readCurrentSession(baseDir) {
  const sessionPath = path.join(baseDir, LUMENFLOW_MEMORY_PATHS.SESSION_CURRENT);
  try {
    const content = await fs.readFile(sessionPath, { encoding: "utf-8" });
    return JSON.parse(content);
  } catch {
    return null;
  }
}
async function inferSessionFromSessionFile(baseDir) {
  let session = await readCurrentSession(baseDir);
  if (session) {
    return session;
  }
  const mainCheckout = await getMainCheckoutFromWorktree(baseDir);
  if (mainCheckout) {
    session = await readCurrentSession(mainCheckout);
    if (session) {
      return session;
    }
  }
  return null;
}
function isValidSessionId(value) {
  if (!value)
    return false;
  if (typeof value !== "string")
    return false;
  return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
}
function isValidWuId(wuId) {
  if (!wuId)
    return true;
  return MEMORY_PATTERNS.WU_ID.test(wuId);
}
function isValidMemoryId(memId) {
  return MEMORY_PATTERNS.MEMORY_ID.test(memId);
}
async function appendRelationship(memoryDir, relationship) {
  const validation = validateRelationship(relationship);
  if (!validation.success) {
    const issues = validation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ");
    throw createError(ErrorCodes.VALIDATION_ERROR, `Relationship validation error: ${issues}`);
  }
  const filePath = path.join(memoryDir, RELATIONSHIPS_FILE_NAME);
  const line = `${JSON.stringify(relationship)}
`;
  await fs.appendFile(filePath, line, { encoding: "utf-8" });
  return relationship;
}
function getLifecycleForType(type) {
  return LIFECYCLE_BY_TYPE[type];
}
async function createMemoryNode(baseDir, options) {
  const { title, type: inputType = DEFAULT_NODE_TYPE, wuId: explicitWuId, sessionId: explicitSessionId, discoveredFrom, tags: inputTags, priority } = options;
  if (title == null) {
    throw createError(ErrorCodes.VALIDATION_ERROR, ERROR_MESSAGES.TITLE_REQUIRED);
  }
  if (title === "") {
    throw createError(ErrorCodes.VALIDATION_ERROR, ERROR_MESSAGES.TITLE_EMPTY);
  }
  const { type: normalizedType, aliasTag } = normalizeType(inputType);
  if (!MEMORY_NODE_TYPES.includes(normalizedType)) {
    throw createError(ErrorCodes.VALIDATION_ERROR, ERROR_MESSAGES.INVALID_TYPE);
  }
  const type = normalizedType;
  let tags = inputTags ? [...inputTags] : [];
  if (aliasTag && !tags.includes(aliasTag)) {
    tags = [aliasTag, ...tags];
  }
  tags = [...new Set(tags)];
  const inferredSession = explicitWuId && explicitSessionId ? null : await inferSessionFromSessionFile(baseDir);
  const wuId = explicitWuId || inferredSession?.wu_id;
  const sessionId = explicitSessionId || (isValidSessionId(inferredSession?.session_id) ? inferredSession.session_id : void 0);
  if (wuId && !isValidWuId(wuId)) {
    throw createError(ErrorCodes.INVALID_WU_ID, ERROR_MESSAGES.WU_ID_INVALID);
  }
  if (discoveredFrom && !isValidMemoryId(discoveredFrom)) {
    throw createError(ErrorCodes.VALIDATION_ERROR, ERROR_MESSAGES.MEMORY_ID_INVALID);
  }
  const memoryDir = await ensureMemoryDir(baseDir);
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
  const idContent = `${title}-${timestamp}`;
  const id = generateMemId(idContent);
  const lifecycle = getLifecycleForType(type);
  const metadata = {};
  if (priority) {
    metadata.priority = priority;
  }
  const node = {
    id,
    type,
    lifecycle,
    content: title,
    created_at: timestamp
  };
  if (wuId) {
    node.wu_id = wuId;
  }
  if (sessionId) {
    node.session_id = sessionId;
  }
  if (Object.keys(metadata).length > 0) {
    node.metadata = metadata;
  }
  if (tags && tags.length > 0) {
    node.tags = tags;
  }
  const nodeValidation = validateMemoryNode(node);
  if (!nodeValidation.success) {
    const issues = nodeValidation.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ");
    throw createError(ErrorCodes.VALIDATION_ERROR, `Node validation error: ${issues}`);
  }
  await appendNode(memoryDir, node);
  const result = {
    success: true,
    node
  };
  if (discoveredFrom) {
    const relationship = {
      from_id: node.id,
      to_id: discoveredFrom,
      type: "discovered_from",
      created_at: timestamp
    };
    await appendRelationship(memoryDir, relationship);
    result.relationship = relationship;
  }
  return result;
}

export {
  createMemoryNode
};
