import {
  assertIsoRecordedAt,
  assertSafePathSegment,
  assertString,
  isRecord,
  optionalString,
  optionalStringArray,
  recordStoreDay,
  validateStringRecord
} from "./chunk-DGXUHMOV.js";
import {
  listJsonFiles,
  readJsonFile
} from "./chunk-LPSF4OQH.js";

// src/commitment-ledger.ts
import path from "path";
import { mkdir, unlink, writeFile } from "fs/promises";
function resolveCommitmentLedgerDir(memoryDir, overrideDir) {
  if (typeof overrideDir === "string" && overrideDir.trim().length > 0) {
    return overrideDir.trim();
  }
  return path.join(memoryDir, "state", "commitment-ledger");
}
function validateCommitmentLedgerEntry(raw) {
  if (!isRecord(raw)) throw new Error("commitment ledger entry must be an object");
  if (raw.schemaVersion !== 1) throw new Error("schemaVersion must be 1");
  const source = assertString(raw.source, "source");
  if (!["tool_result", "cli", "system", "manual"].includes(source)) {
    throw new Error("source must be one of tool_result|cli|system|manual");
  }
  const kind = assertString(raw.kind, "kind");
  if (!["promise", "follow_up", "deadline", "deliverable"].includes(kind)) {
    throw new Error("kind must be one of promise|follow_up|deadline|deliverable");
  }
  const state = assertString(raw.state, "state");
  if (!["open", "fulfilled", "cancelled", "expired"].includes(state)) {
    throw new Error("state must be one of open|fulfilled|cancelled|expired");
  }
  const dueAt = optionalString(raw.dueAt);
  if (dueAt !== void 0) {
    assertIsoRecordedAt(dueAt, "dueAt");
  }
  const stateChangedAt = optionalString(raw.stateChangedAt);
  if (stateChangedAt !== void 0) {
    assertIsoRecordedAt(stateChangedAt, "stateChangedAt");
  }
  const resolvedAt = optionalString(raw.resolvedAt);
  if (resolvedAt !== void 0) {
    assertIsoRecordedAt(resolvedAt, "resolvedAt");
  }
  const normalizedStateChangedAt = stateChangedAt ?? (state === "open" ? void 0 : assertString(raw.recordedAt, "recordedAt"));
  const normalizedResolvedAt = resolvedAt ?? (state === "open" ? void 0 : normalizedStateChangedAt);
  return {
    schemaVersion: 1,
    entryId: assertSafePathSegment(assertString(raw.entryId, "entryId"), "entryId"),
    recordedAt: assertIsoRecordedAt(assertString(raw.recordedAt, "recordedAt")),
    sessionKey: assertString(raw.sessionKey, "sessionKey"),
    source,
    kind,
    state,
    scope: assertString(raw.scope, "scope"),
    summary: assertString(raw.summary, "summary"),
    dueAt,
    entityRefs: optionalStringArray(raw.entityRefs, "entityRefs"),
    workProductEntryRefs: optionalStringArray(raw.workProductEntryRefs, "workProductEntryRefs"),
    objectiveStateSnapshotRefs: optionalStringArray(raw.objectiveStateSnapshotRefs, "objectiveStateSnapshotRefs"),
    tags: optionalStringArray(raw.tags, "tags"),
    metadata: validateStringRecord(raw.metadata, "metadata"),
    stateChangedAt: normalizedStateChangedAt,
    resolvedAt: normalizedResolvedAt
  };
}
async function recordCommitmentLedgerEntry(options) {
  const rootDir = resolveCommitmentLedgerDir(options.memoryDir, options.commitmentLedgerDir);
  const validated = validateCommitmentLedgerEntry(options.entry);
  const day = recordStoreDay(validated.recordedAt);
  const entriesDir = path.join(rootDir, "entries", day);
  const filePath = path.join(entriesDir, `${validated.entryId}.json`);
  await mkdir(entriesDir, { recursive: true });
  await writeFile(filePath, JSON.stringify(validated, null, 2), "utf8");
  return filePath;
}
async function readCommitmentLedgerEntries(options) {
  const rootDir = resolveCommitmentLedgerDir(options.memoryDir, options.commitmentLedgerDir);
  const files = await listJsonFiles(path.join(rootDir, "entries"));
  const entries = [];
  const entryFiles = [];
  const invalidEntries = [];
  for (const filePath of files) {
    try {
      const entry = validateCommitmentLedgerEntry(await readJsonFile(filePath));
      entries.push(entry);
      entryFiles.push({ entry, filePath });
    } catch (error) {
      invalidEntries.push({
        path: filePath,
        error: error instanceof Error ? error.message : String(error)
      });
    }
  }
  return { files, entries, entryFiles, invalidEntries };
}
function isResolvedState(state) {
  return state === "fulfilled" || state === "cancelled" || state === "expired";
}
function isOverdueOpenEntry(entry, nowMs) {
  return entry.state === "open" && typeof entry.dueAt === "string" && Date.parse(entry.dueAt) < nowMs;
}
function isStaleOpenEntry(entry, nowMs, staleDays) {
  if (entry.state !== "open") return false;
  if (typeof entry.dueAt === "string") return false;
  const staleCutoff = nowMs - staleDays * 24 * 60 * 60 * 1e3;
  return Date.parse(entry.recordedAt) < staleCutoff;
}
function isDecayEligibleResolvedEntry(entry, nowMs, decayDays) {
  if (!isResolvedState(entry.state)) return false;
  const reference = entry.resolvedAt ?? entry.stateChangedAt ?? entry.recordedAt;
  const decayCutoff = nowMs - decayDays * 24 * 60 * 60 * 1e3;
  return Date.parse(reference) < decayCutoff;
}
async function findCommitmentLedgerEntryById(options) {
  const { entryFiles } = await readCommitmentLedgerEntries(options);
  for (const candidate of entryFiles) {
    if (candidate.entry.entryId === options.entryId || path.basename(candidate.filePath, ".json") === options.entryId) {
      return candidate;
    }
  }
  return null;
}
async function transitionCommitmentLedgerEntryState(options) {
  const match = await findCommitmentLedgerEntryById(options);
  if (!match) {
    throw new Error(`commitment entry not found: ${options.entryId}`);
  }
  const changedAt = assertIsoRecordedAt(options.changedAt, "changedAt");
  const nextState = options.nextState;
  const nextEntry = {
    ...match.entry,
    state: nextState,
    stateChangedAt: changedAt,
    resolvedAt: isResolvedState(nextState) ? changedAt : void 0
  };
  await writeFile(match.filePath, JSON.stringify(validateCommitmentLedgerEntry(nextEntry), null, 2), "utf8");
  return nextEntry;
}
async function applyCommitmentLedgerLifecycle(options) {
  if (!options.enabled) {
    return { transitionedToExpired: [], deletedResolved: [] };
  }
  const nowIso = assertIsoRecordedAt(options.now ?? (/* @__PURE__ */ new Date()).toISOString(), "now");
  const nowMs = Date.parse(nowIso);
  const { entryFiles } = await readCommitmentLedgerEntries(options);
  const transitionedToExpired = [];
  const deletedResolved = [];
  for (const { entry, filePath } of entryFiles) {
    if (isOverdueOpenEntry(entry, nowMs)) {
      const updated = validateCommitmentLedgerEntry({
        ...entry,
        state: "expired",
        stateChangedAt: nowIso,
        resolvedAt: nowIso
      });
      await writeFile(filePath, JSON.stringify(updated, null, 2), "utf8");
      transitionedToExpired.push(updated);
      continue;
    }
    if (isDecayEligibleResolvedEntry(entry, nowMs, options.decayDays)) {
      await unlink(filePath);
      deletedResolved.push(entry);
    }
  }
  return { transitionedToExpired, deletedResolved };
}
async function getCommitmentLedgerStatus(options) {
  const rootDir = resolveCommitmentLedgerDir(options.memoryDir, options.commitmentLedgerDir);
  const entriesDir = path.join(rootDir, "entries");
  const { files, entries, invalidEntries } = await readCommitmentLedgerEntries(options);
  entries.sort((a, b) => b.recordedAt.localeCompare(a.recordedAt));
  const nowMs = Date.parse(assertIsoRecordedAt(options.now ?? (/* @__PURE__ */ new Date()).toISOString(), "now"));
  const staleDays = Math.max(1, Math.floor(options.staleDays ?? 14));
  const decayDays = Math.max(1, Math.floor(options.decayDays ?? 90));
  const byKind = {};
  const byState = {};
  for (const entry of entries) {
    byKind[entry.kind] = (byKind[entry.kind] ?? 0) + 1;
    byState[entry.state] = (byState[entry.state] ?? 0) + 1;
  }
  return {
    enabled: options.enabled,
    rootDir,
    entriesDir,
    entries: {
      total: files.length,
      valid: entries.length,
      invalid: invalidEntries.length,
      byKind,
      byState,
      latestEntryId: entries[0]?.entryId,
      latestRecordedAt: entries[0]?.recordedAt,
      latestSessionKey: entries[0]?.sessionKey
    },
    latestEntry: entries[0],
    invalidEntries,
    lifecycle: options.lifecycleEnabled ? {
      overdueOpen: entries.filter((entry) => isOverdueOpenEntry(entry, nowMs)).length,
      staleOpen: entries.filter((entry) => isStaleOpenEntry(entry, nowMs, staleDays)).length,
      decayEligibleResolved: entries.filter((entry) => isDecayEligibleResolvedEntry(entry, nowMs, decayDays)).length
    } : void 0
  };
}

export {
  resolveCommitmentLedgerDir,
  validateCommitmentLedgerEntry,
  recordCommitmentLedgerEntry,
  transitionCommitmentLedgerEntryState,
  applyCommitmentLedgerLifecycle,
  getCommitmentLedgerStatus
};
//# sourceMappingURL=chunk-FYIYMQ5N.js.map