import {
  applyUtilityPromotionRuntimePolicy,
  loadUtilityRuntimeValues
} from "./chunk-FSFEQI74.js";
import {
  computeTierValueScore,
  decideTierTransition
} from "./chunk-S75M5ZRK.js";
import "./chunk-PYXS46O7.js";
import "./chunk-3QKK7QOS.js";
import {
  computeLifecycleValueInputs
} from "./chunk-TBBDFYXW.js";
import "./chunk-DGXUHMOV.js";
import "./chunk-LPSF4OQH.js";
import "./chunk-PZ5AY32C.js";

// src/maintenance/tier-stats.ts
async function readTierVisibleMemories(storage) {
  const [hotMemories, coldMemories] = await Promise.all([
    storage.readAllMemories(),
    storage.readAllColdMemories()
  ]);
  return [
    ...hotMemories.map((memory) => ({ memory, tier: "hot" })),
    ...coldMemories.map((memory) => ({ memory, tier: "cold" }))
  ];
}
async function tierRoutingPolicyFromConfig(config) {
  const basePolicy = {
    enabled: config.qmdTierMigrationEnabled,
    demotionMinAgeDays: config.qmdTierDemotionMinAgeDays,
    demotionValueThreshold: config.qmdTierDemotionValueThreshold,
    promotionValueThreshold: config.qmdTierPromotionValueThreshold
  };
  const runtime = await loadUtilityRuntimeValues({
    memoryDir: config.memoryDir,
    memoryUtilityLearningEnabled: config.memoryUtilityLearningEnabled,
    promotionByOutcomeEnabled: config.promotionByOutcomeEnabled
  });
  return applyUtilityPromotionRuntimePolicy(basePolicy, runtime);
}
async function summarizeTiers(storage) {
  const all = await readTierVisibleMemories(storage);
  const summary = {
    total: all.length,
    byTier: { hot: 0, cold: 0 },
    byStatus: {},
    forgottenCount: 0,
    byCategory: {}
  };
  for (const { memory: m, tier } of all) {
    summary.byTier[tier] += 1;
    const status = m.frontmatter.status ?? "active";
    summary.byStatus[status] = (summary.byStatus[status] ?? 0) + 1;
    if (status === "forgotten") summary.forgottenCount += 1;
    const cat = m.frontmatter.category ?? "(uncategorized)";
    summary.byCategory[cat] = (summary.byCategory[cat] ?? 0) + 1;
  }
  return summary;
}
async function explainTierForMemory(storage, id, config) {
  const trimmed = typeof id === "string" ? id.trim() : "";
  if (trimmed.length === 0) {
    throw new Error("tier explain: memory id is required and must be non-empty");
  }
  const all = await readTierVisibleMemories(storage);
  const entry = all.find(({ memory: m }) => m.frontmatter.id === trimmed);
  if (!entry) {
    throw new Error(`tier explain: memory not found: ${trimmed}`);
  }
  const { memory, tier: currentTier } = entry;
  const now = /* @__PURE__ */ new Date();
  const valueInputs = computeLifecycleValueInputs(memory, now);
  const valueScore = computeTierValueScore(memory, now);
  const policy = await tierRoutingPolicyFromConfig(config);
  const decision = decideTierTransition(memory, currentTier, policy, now);
  const fm = memory.frontmatter;
  return {
    id: trimmed,
    path: memory.path,
    currentTier,
    status: typeof fm.status === "string" ? fm.status : "active",
    category: typeof fm.category === "string" ? fm.category : "",
    valueScore,
    decision,
    signals: {
      confidence: valueInputs.confidence,
      accessCount: typeof fm.accessCount === "number" ? fm.accessCount : 0,
      lastAccessed: typeof fm.lastAccessed === "string" ? fm.lastAccessed : null,
      created: typeof fm.created === "string" ? fm.created : "",
      updated: typeof fm.updated === "string" ? fm.updated : "",
      importance: valueInputs.importance,
      feedback: valueInputs.feedback
    }
  };
}
function formatTierSummaryText(summary) {
  const lines = [];
  lines.push("=== Memory Tier Distribution ===");
  lines.push(`Total memories: ${summary.total}`);
  lines.push("");
  lines.push("Tier:");
  lines.push(`  hot:  ${summary.byTier.hot}`);
  lines.push(`  cold: ${summary.byTier.cold}`);
  lines.push("");
  lines.push("Status:");
  const statusEntries = Object.entries(summary.byStatus).sort(
    (a, b) => b[1] - a[1] || a[0].localeCompare(b[0])
  );
  for (const [status, count] of statusEntries) {
    lines.push(`  ${status}: ${count}`);
  }
  lines.push("");
  lines.push("Top categories:");
  const categoryEntries = Object.entries(summary.byCategory).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, 8);
  for (const [cat, count] of categoryEntries) {
    lines.push(`  ${cat}: ${count}`);
  }
  return lines.join("\n");
}
function formatTierExplainText(explain) {
  const lines = [];
  lines.push(`=== Tier Explain: ${explain.id} ===`);
  lines.push(`path:          ${explain.path}`);
  lines.push(`current tier:  ${explain.currentTier}`);
  lines.push(`status:        ${explain.status}`);
  lines.push(`category:      ${explain.category}`);
  lines.push(`value score:   ${explain.valueScore.toFixed(3)}`);
  lines.push("");
  lines.push("Tier-transition decision:");
  lines.push(`  next tier: ${explain.decision.nextTier}`);
  lines.push(`  changed:   ${explain.decision.changed}`);
  lines.push(`  reason:    ${explain.decision.reason}`);
  lines.push("");
  lines.push("Signals:");
  lines.push(`  confidence:   ${explain.signals.confidence}`);
  lines.push(`  accessCount:  ${explain.signals.accessCount}`);
  lines.push(`  lastAccessed: ${explain.signals.lastAccessed ?? "(never)"}`);
  lines.push(`  created:      ${explain.signals.created}`);
  lines.push(`  updated:      ${explain.signals.updated}`);
  lines.push(`  importance:   ${explain.signals.importance}`);
  lines.push(`  feedback:     ${explain.signals.feedback}`);
  return lines.join("\n");
}
export {
  explainTierForMemory,
  formatTierExplainText,
  formatTierSummaryText,
  summarizeTiers
};
//# sourceMappingURL=tier-stats-62ZVDFKS.js.map