import {
  startSession
} from "./chunk-GTFJB67L.js";
import {
  parseYAML
} from "./chunk-NRIZR3A7.js";
import {
  CONFIG_FILES,
  LUMENFLOW_PATHS
} from "./chunk-DWMLTXKQ.js";

// ../agent/dist/auto-session-integration.js
import { randomUUID } from "crypto";
import { readFileSync, writeFileSync, existsSync, unlinkSync, mkdirSync } from "fs";
import { join } from "path";

// ../memory/dist/mem-index-core.js
import fs from "fs/promises";
import path from "path";
import crypto from "crypto";

// ../memory/dist/mem-promote-core.js
import fs2 from "fs/promises";
import path2 from "path";
var ALLOWED_PROMOTION_TAGS = [
  "decision",
  "convention",
  "pattern",
  "pitfall",
  "interface",
  "invariant",
  "faq"
];
var ERROR_MESSAGES = {
  NODE_NOT_FOUND: "Node not found",
  ALREADY_PROJECT: "Node is already at project lifecycle",
  INVALID_TAG: `Tag must be one of: ${ALLOWED_PROMOTION_TAGS.join(", ")}`,
  INVALID_WU_ID: "Invalid WU ID format. Expected pattern: WU-XXX (e.g., WU-1234)"
};

// ../memory/dist/memory-promotion.js
import fs3 from "fs/promises";
import path3 from "path";

// ../memory/dist/mem-profile-core.js
import path4 from "path";

// ../memory/dist/control-plane-sync-adapter.js
import fs4 from "fs/promises";
import path5 from "path";
var DEFAULT_CONTROL_PLANE_SYNC_STATE_PATH = path5.join(".lumenflow", "state", "control-plane-sync.json");

// ../agent/dist/auto-session-integration.js
var SESSION_FILENAME = "current.json";
var WORKSPACE_CONFIG_FILE = CONFIG_FILES.WORKSPACE_CONFIG;
var CONTROL_PLANE_REGISTER_PATH = "/api/v1/sessions/register";
var CONTROL_PLANE_DEREGISTER_PATH = "/api/v1/sessions/deregister";
var DEFAULT_TIER = 2;
var DEFAULT_AGENT_TYPE = "claude-code";
var DEFAULT_AGENT_VERSION = "unknown";
var DEFAULT_HOST_ID = "unknown";
var DEFAULT_AGENT_CAPABILITIES = ["session_lifecycle", "heartbeat"];
var AGENT_CAPABILITIES_ENV = "LUMENFLOW_AGENT_CAPABILITIES";
var AGENT_VERSION_ENV = "LUMENFLOW_AGENT_VERSION";
var CONTEXT_TIER_MAP = {
  1: "minimal",
  2: "core",
  3: "full"
};
function parseCapabilities(rawValue) {
  if (!rawValue) {
    return [...DEFAULT_AGENT_CAPABILITIES];
  }
  const parsed = rawValue.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0);
  return parsed.length > 0 ? parsed : [...DEFAULT_AGENT_CAPABILITIES];
}
function asNonEmptyString(value) {
  return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
}
function normalizeEndpoint(endpoint) {
  return endpoint.endsWith("/") ? endpoint.slice(0, endpoint.length - 1) : endpoint;
}
function resolveControlPlaneSessionSyncConfig(workspaceRoot, environment) {
  const workspacePath = join(workspaceRoot, WORKSPACE_CONFIG_FILE);
  if (!existsSync(workspacePath)) {
    return null;
  }
  let parsedWorkspace;
  try {
    parsedWorkspace = parseYAML(readFileSync(workspacePath, { encoding: "utf-8" }));
  } catch {
    return null;
  }
  const workspaceId = asNonEmptyString(parsedWorkspace?.id);
  const endpoint = asNonEmptyString(parsedWorkspace?.control_plane?.endpoint);
  const tokenEnv = asNonEmptyString(parsedWorkspace?.control_plane?.auth?.token_env);
  if (!workspaceId || !endpoint || !tokenEnv) {
    return null;
  }
  const token = asNonEmptyString(environment[tokenEnv]);
  if (!token) {
    return null;
  }
  try {
    void new URL(endpoint);
  } catch {
    return null;
  }
  return {
    workspaceId,
    endpoint: normalizeEndpoint(endpoint),
    token
  };
}
function resolveStandardSessionMetadata(input) {
  const clientType = input.agentType;
  const capabilities = parseCapabilities(asNonEmptyString(input.environment[AGENT_CAPABILITIES_ENV]));
  const agentVersion = asNonEmptyString(input.environment[AGENT_VERSION_ENV]) ?? DEFAULT_AGENT_VERSION;
  const hostId = asNonEmptyString(input.environment.HOSTNAME) ?? asNonEmptyString(input.environment.COMPUTERNAME) ?? DEFAULT_HOST_ID;
  return {
    client_type: clientType,
    capabilities,
    agent_version: agentVersion,
    host_id: hostId,
    metadata: {
      client_type: clientType,
      capabilities,
      agent_version: agentVersion,
      host_id: hostId
    }
  };
}
async function postControlPlaneSessionHook(endpoint, token, path6, payload, fetchFn) {
  const response = await fetchFn(`${endpoint}${path6}`, {
    method: "POST",
    headers: {
      authorization: `Bearer ${token}`,
      "content-type": "application/json"
    },
    body: JSON.stringify(payload)
  });
  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`);
  }
}
function getSessionFilePath(sessionDir) {
  return join(sessionDir, SESSION_FILENAME);
}
async function startSessionForWU(options) {
  const { wuId, tier = DEFAULT_TIER, agentType = DEFAULT_AGENT_TYPE, lane, sessionDir, workspaceRoot = process.cwd(), environment = process.env, controlPlaneSyncPort, fetchFn = fetch, baseDir = process.cwd() } = options;
  const sessDir = sessionDir ?? LUMENFLOW_PATHS.SESSIONS;
  const sessionFile = getSessionFilePath(sessDir);
  if (existsSync(sessionFile)) {
    const existing = JSON.parse(readFileSync(sessionFile, { encoding: "utf-8" }));
    return {
      sessionId: existing.session_id,
      alreadyActive: true
    };
  }
  if (!existsSync(sessDir)) {
    mkdirSync(sessDir, { recursive: true });
  }
  const sessionId = randomUUID();
  const session = {
    session_id: sessionId,
    wu_id: wuId,
    started: (/* @__PURE__ */ new Date()).toISOString(),
    agent_type: agentType,
    context_tier: tier,
    incidents_logged: 0,
    incidents_major: 0,
    auto_started: true
    // Mark as auto-started by wu:claim
  };
  writeFileSync(sessionFile, JSON.stringify(session, null, 2), { encoding: "utf-8" });
  let memoryNodeId = null;
  try {
    const memResult = await startSession(baseDir, {
      wuId,
      agentType,
      contextTier: CONTEXT_TIER_MAP[tier] ?? "full"
    });
    memoryNodeId = memResult.session?.id ?? null;
  } catch {
  }
  const controlPlaneConfig = resolveControlPlaneSessionSyncConfig(workspaceRoot, environment);
  if (controlPlaneConfig) {
    const standardizedMetadata = resolveStandardSessionMetadata({
      agentType,
      environment
    });
    const registerInput = {
      workspace_id: controlPlaneConfig.workspaceId,
      session_id: sessionId,
      agent_id: agentType,
      started_at: session.started,
      lane,
      wu_id: wuId,
      client_type: standardizedMetadata.client_type,
      capabilities: standardizedMetadata.capabilities,
      agent_version: standardizedMetadata.agent_version,
      host_id: standardizedMetadata.host_id,
      metadata: standardizedMetadata.metadata
    };
    try {
      if (controlPlaneSyncPort) {
        await controlPlaneSyncPort.registerSession(registerInput);
      } else {
        await postControlPlaneSessionHook(controlPlaneConfig.endpoint, controlPlaneConfig.token, CONTROL_PLANE_REGISTER_PATH, registerInput, fetchFn);
      }
    } catch {
    }
  }
  return {
    sessionId,
    alreadyActive: false,
    memoryNodeId
  };
}
function endSessionForWU(options = {}) {
  const { sessionDir, workspaceRoot = process.cwd(), environment = process.env, controlPlaneSyncPort, fetchFn = fetch } = options;
  const sessDir = sessionDir ?? LUMENFLOW_PATHS.SESSIONS;
  const sessionFile = getSessionFilePath(sessDir);
  if (!existsSync(sessionFile)) {
    return {
      ended: false,
      reason: "no_active_session"
    };
  }
  const session = JSON.parse(readFileSync(sessionFile, { encoding: "utf-8" }));
  session.completed = (/* @__PURE__ */ new Date()).toISOString();
  const summary = {
    wu_id: session.wu_id,
    session_id: session.session_id,
    started: session.started,
    completed: session.completed,
    agent_type: session.agent_type,
    context_tier: session.context_tier,
    incidents_logged: session.incidents_logged,
    incidents_major: session.incidents_major
  };
  unlinkSync(sessionFile);
  const controlPlaneConfig = resolveControlPlaneSessionSyncConfig(workspaceRoot, environment);
  if (controlPlaneConfig) {
    const deregisterInput = {
      workspace_id: controlPlaneConfig.workspaceId,
      session_id: session.session_id,
      ended_at: session.completed,
      reason: "wu_done"
    };
    if (controlPlaneSyncPort) {
      void controlPlaneSyncPort.deregisterSession(deregisterInput).catch(() => {
      });
    } else {
      void postControlPlaneSessionHook(controlPlaneConfig.endpoint, controlPlaneConfig.token, CONTROL_PLANE_DEREGISTER_PATH, deregisterInput, fetchFn).catch(() => {
      });
    }
  }
  return {
    ended: true,
    summary
  };
}
function getCurrentSessionForWU(options = {}) {
  const { sessionDir } = options;
  const sessDir = sessionDir ?? LUMENFLOW_PATHS.SESSIONS;
  const sessionFile = getSessionFilePath(sessDir);
  if (!existsSync(sessionFile)) {
    return null;
  }
  return JSON.parse(readFileSync(sessionFile, { encoding: "utf-8" }));
}

export {
  startSessionForWU,
  endSessionForWU,
  getCurrentSessionForWU
};
