// src/contradiction/contradiction-review.ts
import fs from "fs";
import path from "path";
import { createHash } from "crypto";
function computePairId(memoryIdA, memoryIdB) {
  const sorted = [memoryIdA, memoryIdB].sort();
  return createHash("sha256").update(sorted.join("::")).digest("hex").slice(0, 24);
}
function reviewDir(memoryDir) {
  return path.join(memoryDir, ".review", "contradictions");
}
function pairPath(memoryDir, pairId) {
  if (pairId.includes("/") || pairId.includes("\\") || pairId.includes("..")) {
    throw new Error(`Invalid pairId: ${pairId}`);
  }
  return path.join(reviewDir(memoryDir), `${pairId}.json`);
}
function ensureDir(memoryDir) {
  const dir = reviewDir(memoryDir);
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
}
function writePair(memoryDir, pair) {
  ensureDir(memoryDir);
  const pairId = computePairId(pair.memoryIds[0], pair.memoryIds[1]);
  const existing = readPair(memoryDir, pairId);
  if (existing?.resolution) {
    return existing;
  }
  if (existing && existing.confidence >= pair.confidence) {
    return existing;
  }
  const full = {
    ...pair,
    pairId,
    lastReviewedAt: existing?.lastReviewedAt,
    resolution: existing?.resolution
  };
  const filePath = pairPath(memoryDir, pairId);
  const tmpPath = `${filePath}.tmp`;
  fs.writeFileSync(tmpPath, JSON.stringify(full, null, 2), "utf-8");
  fs.renameSync(tmpPath, filePath);
  return full;
}
function writePairs(memoryDir, pairs) {
  const seen = /* @__PURE__ */ new Set();
  const results = [];
  for (const pair of pairs) {
    const key = computePairId(pair.memoryIds[0], pair.memoryIds[1]);
    if (seen.has(key)) continue;
    seen.add(key);
    results.push(writePair(memoryDir, pair));
  }
  return results;
}
function readPair(memoryDir, pairId) {
  const filePath = pairPath(memoryDir, pairId);
  try {
    const raw = fs.readFileSync(filePath, "utf-8");
    const parsed = JSON.parse(raw);
    if (typeof parsed === "object" && parsed !== null && Array.isArray(parsed.memoryIds)) {
      return parsed;
    }
    return null;
  } catch {
    return null;
  }
}
function listPairs(memoryDir, options) {
  const startTime = Date.now();
  const dir = reviewDir(memoryDir);
  const { filter = "all", namespace, limit = 50 } = options ?? {};
  const pairs = [];
  let total = 0;
  if (!fs.existsSync(dir)) {
    return { pairs: [], total: 0, durationMs: Date.now() - startTime };
  }
  for (const entry of fs.readdirSync(dir)) {
    if (!entry.endsWith(".json")) continue;
    try {
      const raw = fs.readFileSync(path.join(dir, entry), "utf-8");
      const pair = JSON.parse(raw);
      if (typeof pair !== "object" || pair === null) continue;
      if (!Array.isArray(pair.memoryIds)) continue;
      if (namespace && pair.namespace !== namespace) continue;
      if (filter === "unresolved") {
        if (pair.resolution) continue;
        if (pair.verdict === "independent") continue;
      } else if (filter !== "all" && pair.verdict !== filter) {
        continue;
      }
      total++;
      if (pairs.length < limit) pairs.push(pair);
    } catch {
      continue;
    }
  }
  return { pairs, total, durationMs: Date.now() - startTime };
}
function isCoolingDown(pair, cooldownDays) {
  if (cooldownDays <= 0) return false;
  if (!pair.lastReviewedAt) return false;
  const lastReviewed = new Date(pair.lastReviewedAt).getTime();
  if (!Number.isFinite(lastReviewed)) return false;
  const cooldownMs = cooldownDays * 24 * 60 * 60 * 1e3;
  return Date.now() < lastReviewed + cooldownMs;
}
function resolvePair(memoryDir, pairId, verb) {
  const existing = readPair(memoryDir, pairId);
  if (!existing) return null;
  const updated = {
    ...existing,
    lastReviewedAt: (/* @__PURE__ */ new Date()).toISOString(),
    resolution: verb
  };
  const filePath = pairPath(memoryDir, pairId);
  const tmpPath = `${filePath}.tmp`;
  fs.writeFileSync(tmpPath, JSON.stringify(updated, null, 2), "utf-8");
  fs.renameSync(tmpPath, filePath);
  return updated;
}
function memoryHashesChanged(_memoryDir, _pair, _getCurrentHash) {
  return false;
}

export {
  computePairId,
  writePair,
  writePairs,
  readPair,
  listPairs,
  isCoolingDown,
  resolvePair,
  memoryHashesChanged
};
//# sourceMappingURL=chunk-YNB73F22.js.map