// src/tier-migration.ts
import { appendFile, mkdir } from "fs/promises";
import path from "path";
var TierMigrationExecutor = class {
  storage;
  qmd;
  hotCollection;
  coldCollection;
  autoEmbed;
  journalPath;
  constructor(options) {
    this.storage = options.storage;
    this.qmd = options.qmd;
    this.hotCollection = options.hotCollection;
    this.coldCollection = options.coldCollection;
    this.autoEmbed = options.autoEmbed === true;
    this.journalPath = options.journalPath ?? path.join(this.storage.dir, "state", "tier-migration-journal.jsonl");
  }
  async migrateMemory(request) {
    const { memory, fromTier, toTier, reason } = request;
    const targetPath = this.storage.buildTierMemoryPath(memory, toTier);
    if (fromTier === toTier) {
      const noChange = {
        memoryId: memory.frontmatter.id,
        fromTier,
        toTier,
        changed: false,
        reason,
        targetPath
      };
      await this.appendJournal(noChange);
      return noChange;
    }
    const moved = await this.storage.migrateMemoryToTier(memory, toTier);
    const result = {
      memoryId: memory.frontmatter.id,
      fromTier,
      toTier,
      changed: moved.changed,
      reason,
      targetPath: moved.targetPath
    };
    await this.appendJournal(result);
    if (result.changed) {
      const destinationCollection = this.collectionForTier(toTier);
      const sourceCollection = this.collectionForTier(fromTier);
      await this.qmd.updateCollection(destinationCollection);
      if (this.autoEmbed) {
        await this.qmd.embedCollection(destinationCollection);
        if (sourceCollection !== destinationCollection) {
          await this.qmd.embedCollection(sourceCollection);
        }
      }
    }
    return result;
  }
  collectionForTier(tier) {
    return tier === "cold" ? this.coldCollection : this.hotCollection;
  }
  async appendJournal(result) {
    const entry = {
      ts: (/* @__PURE__ */ new Date()).toISOString(),
      memoryId: result.memoryId,
      fromTier: result.fromTier,
      toTier: result.toTier,
      changed: result.changed,
      reason: result.reason,
      targetPath: result.targetPath
    };
    await mkdir(path.dirname(this.journalPath), { recursive: true });
    await appendFile(this.journalPath, `${JSON.stringify(entry)}
`, "utf-8");
  }
};

export {
  TierMigrationExecutor
};
//# sourceMappingURL=chunk-Z5AAYHUC.js.map