import "../chunk-2ESYSVXG.js";

// src/sync/memory-sync.ts
async function syncMemoryStores(opts) {
  const { sessionId, sandboxName, provider, secrets } = opts;
  const { listResources } = await import("../db/session-resources.js");
  const { getMemoryStore, listMemories, createOrUpsertMemory, getMemoryByPath, deleteMemory } = await import("../db/memory.js");
  const resources = listResources(sessionId);
  const memStoreResources = resources.filter(
    (r) => r.type === "memory_store" && r.memory_store_id && r.access === "read_write"
  );
  if (memStoreResources.length === 0) return;
  for (const r of memStoreResources) {
    const store = getMemoryStore(r.memory_store_id);
    if (!store) continue;
    const storeName = store.name.replace(/[^a-zA-Z0-9_.-]/g, "_");
    const storeDir = `/mnt/memory/${storeName}`;
    let containerPaths;
    try {
      const result = await provider.exec(
        sandboxName,
        ["find", storeDir, "-type", "f"],
        { secrets, timeoutMs: 1e4 }
      );
      if (result.exit_code !== 0 || !result.stdout.trim()) {
        containerPaths = [];
      } else {
        const clean = result.stdout.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, "");
        containerPaths = clean.trim().split("\n").map((l) => l.trim()).filter(Boolean);
      }
    } catch (err) {
      console.warn(`[memory-sync] failed to list files in ${storeDir}:`, err);
      continue;
    }
    const prefix = storeDir.endsWith("/") ? storeDir : `${storeDir}/`;
    const containerFileMap = /* @__PURE__ */ new Map();
    for (const absPath of containerPaths) {
      if (absPath.startsWith(prefix)) {
        const relPath = absPath.slice(prefix.length);
        if (relPath) containerFileMap.set(relPath, absPath);
      }
    }
    const dbMemories = listMemories(store.id);
    const dbMemoryMap = new Map(dbMemories.map((m) => [m.path, m]));
    for (const [relPath, absPath] of containerFileMap) {
      try {
        const result = await provider.exec(
          sandboxName,
          ["cat", "--", absPath],
          { secrets, timeoutMs: 1e4 }
        );
        if (result.exit_code !== 0) continue;
        const content = result.stdout.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, "");
        const existing = dbMemoryMap.get(relPath);
        if (existing) {
          if (existing.content !== content) {
            createOrUpsertMemory(store.id, relPath, content, sessionId);
          }
        } else {
          createOrUpsertMemory(store.id, relPath, content, sessionId);
        }
      } catch (err) {
        console.warn(`[memory-sync] failed to read ${absPath}:`, err);
      }
    }
    for (const [path, mem] of dbMemoryMap) {
      if (!containerFileMap.has(path)) {
        try {
          deleteMemory(mem.id, sessionId);
        } catch (err) {
          console.warn(`[memory-sync] failed to delete memory ${mem.id}:`, err);
        }
      }
    }
  }
}
export {
  syncMemoryStores
};
