import {
  reviewSessions
} from "./chunk-42HZLSXP.js";
import {
  archiveMemoryStore,
  createMemoryStore,
  createOrUpsertMemory,
  deleteMemory,
  deleteMemoryStore,
  getMemory,
  getMemoryStore,
  getMemoryVersion,
  listMemories,
  listMemoryStores,
  listMemoryVersions,
  redactMemoryVersion,
  updateMemory,
  updateMemoryStore
} from "./chunk-2UKAINAN.js";
import {
  assertResourceTenant,
  tenantFilter
} from "./chunk-K7DLILHK.js";
import {
  jsonOk,
  paginatedOk,
  routeWrap
} from "./chunk-ZMMFMEXX.js";
import {
  getConfig
} from "./chunk-2MAQ6JFL.js";
import {
  getDb,
  init_client
} from "./chunk-TLEKKGH7.js";
import {
  badRequest,
  conflict,
  notFound,
  tooManyRequests
} from "./chunk-EZYKRG4W.js";

// src/handlers/memory.ts
import { z } from "zod";
init_client();
function assertStoreTenant(auth, storeAgentId) {
  if (storeAgentId == null) {
    if (!auth.isGlobalAdmin) throw notFound("memory store not found");
    return;
  }
  const row = getDb().prepare(`SELECT tenant_id FROM agents WHERE id = ?`).get(storeAgentId);
  if (!row) throw notFound("memory store not found");
  assertResourceTenant(auth, row.tenant_id, "memory store not found");
}
function loadStoreForCaller(auth, id) {
  const store = getMemoryStore(id);
  if (!store) throw notFound(`memory store not found: ${id}`);
  assertStoreTenant(auth, store.agent_id);
  return store;
}
var CreateStoreSchema = z.object({
  name: z.string().min(1),
  description: z.string().optional(),
  agent_id: z.string().min(1)
});
function handleCreateMemoryStore(request) {
  return routeWrap(request, async ({ auth }) => {
    const body = await request.json();
    const parsed = CreateStoreSchema.safeParse(body);
    if (!parsed.success) throw badRequest(parsed.error.message);
    const agentRow = getDb().prepare(`SELECT tenant_id FROM agents WHERE id = ?`).get(parsed.data.agent_id);
    if (!agentRow) throw notFound(`agent not found: ${parsed.data.agent_id}`);
    assertResourceTenant(auth, agentRow.tenant_id, `agent not found: ${parsed.data.agent_id}`);
    const store = createMemoryStore({
      name: parsed.data.name,
      description: parsed.data.description,
      agent_id: parsed.data.agent_id
    });
    return jsonOk(store, 201);
  });
}
function handleListMemoryStores(request) {
  return routeWrap(request, async ({ auth, request: req }) => {
    const url = new URL(req.url);
    const agentId = url.searchParams.get("agent_id") ?? void 0;
    const requestedLimit = Number(url.searchParams.get("limit") || "100");
    const data = listMemoryStores({
      agent_id: agentId,
      tenantFilter: tenantFilter(auth)
    });
    return paginatedOk(data, requestedLimit);
  });
}
function handleGetMemoryStore(request, id) {
  return routeWrap(request, async ({ auth }) => {
    const store = loadStoreForCaller(auth, id);
    return jsonOk(store);
  });
}
function handleDeleteMemoryStore(request, id) {
  return routeWrap(request, async ({ auth }) => {
    loadStoreForCaller(auth, id);
    const deleted = deleteMemoryStore(id);
    if (!deleted) throw notFound(`memory store not found: ${id}`);
    return jsonOk({ id, type: "memory_store_deleted" });
  });
}
var UpdateStoreSchema = z.object({
  name: z.string().min(1).optional(),
  description: z.string().optional(),
  metadata: z.record(z.string()).optional()
});
function handleUpdateMemoryStore(request, id) {
  return routeWrap(request, async ({ auth }) => {
    loadStoreForCaller(auth, id);
    const body = await request.json();
    const parsed = UpdateStoreSchema.safeParse(body);
    if (!parsed.success) throw badRequest(parsed.error.message);
    const store = updateMemoryStore(id, parsed.data);
    if (!store) throw notFound(`memory store not found: ${id}`);
    return jsonOk(store);
  });
}
var CreateMemorySchema = z.object({
  path: z.string().min(1),
  content: z.string()
});
var UpdateMemorySchema = z.object({
  content: z.string(),
  content_sha256: z.string().optional()
});
function handleCreateMemory(request, storeId) {
  return routeWrap(request, async ({ auth }) => {
    loadStoreForCaller(auth, storeId);
    const body = await request.json();
    const parsed = CreateMemorySchema.safeParse(body);
    if (!parsed.success) throw badRequest(parsed.error.message);
    const memory = createOrUpsertMemory(storeId, parsed.data.path, parsed.data.content);
    return jsonOk(memory, 201);
  });
}
function handleListMemories(request, storeId) {
  return routeWrap(request, async ({ auth, request: req }) => {
    loadStoreForCaller(auth, storeId);
    const url = new URL(req.url);
    const requestedLimit = Number(url.searchParams.get("limit") || "100");
    const data = listMemories(storeId);
    return paginatedOk(data, requestedLimit);
  });
}
function handleGetMemory(request, storeId, memId) {
  return routeWrap(request, async ({ auth }) => {
    loadStoreForCaller(auth, storeId);
    const memory = getMemory(memId);
    if (!memory || memory.store_id !== storeId) throw notFound(`memory not found: ${memId}`);
    return jsonOk(memory);
  });
}
function handleUpdateMemory(request, storeId, memId) {
  return routeWrap(request, async ({ auth }) => {
    loadStoreForCaller(auth, storeId);
    const body = await request.json();
    const parsed = UpdateMemorySchema.safeParse(body);
    if (!parsed.success) throw badRequest(parsed.error.message);
    const { memory, conflict: isConflict } = updateMemory(
      memId,
      parsed.data.content,
      parsed.data.content_sha256
    );
    if (isConflict) {
      throw conflict(
        `content_sha256 precondition failed: the memory has been modified since you last read it. Re-read and retry.`
      );
    }
    if (!memory) throw notFound(`memory not found: ${memId}`);
    return jsonOk(memory);
  });
}
function handleDeleteMemory(request, storeId, memId) {
  return routeWrap(request, async ({ auth }) => {
    loadStoreForCaller(auth, storeId);
    const deleted = deleteMemory(memId);
    if (!deleted) throw notFound(`memory not found: ${memId}`);
    return jsonOk({ id: memId, type: "memory_deleted" });
  });
}
function handleListMemoryVersions(request, storeId) {
  return routeWrap(request, async ({ auth, request: req }) => {
    loadStoreForCaller(auth, storeId);
    const url = new URL(req.url);
    const memoryId = url.searchParams.get("memory_id") ?? void 0;
    const requestedLimit = Number(url.searchParams.get("limit") || "100");
    const cursor = url.searchParams.get("cursor") ?? void 0;
    const data = listMemoryVersions(storeId, {
      memoryId,
      limit: requestedLimit,
      cursor
    });
    return paginatedOk(data, requestedLimit);
  });
}
function handleGetMemoryVersion(request, storeId, versionId) {
  return routeWrap(request, async ({ auth }) => {
    loadStoreForCaller(auth, storeId);
    const version = getMemoryVersion(storeId, versionId);
    if (!version) throw notFound(`memory version not found: ${versionId}`);
    return jsonOk(version);
  });
}
function handleRedactMemoryVersion(request, storeId, versionId) {
  return routeWrap(request, async ({ auth }) => {
    loadStoreForCaller(auth, storeId);
    const version = getMemoryVersion(storeId, versionId);
    if (!version) throw notFound(`memory version not found: ${versionId}`);
    const redacted = redactMemoryVersion(storeId, versionId);
    if (!redacted) throw badRequest(`cannot redact this version: it is the current head of a live memory`);
    const updated = getMemoryVersion(storeId, versionId);
    return jsonOk(updated);
  });
}
function handleArchiveMemoryStore(request, storeId) {
  return routeWrap(request, async ({ auth }) => {
    loadStoreForCaller(auth, storeId);
    const archived = archiveMemoryStore(storeId);
    if (!archived) throw notFound(`memory store not found: ${storeId}`);
    const store = getMemoryStore(storeId);
    return jsonOk(store);
  });
}
var DreamRequestSchema = z.object({
  lookback_hours: z.number().min(1).max(720).default(24),
  dry_run: z.boolean().default(false),
  model: z.string().optional(),
  api_key: z.string().optional()
});
var dreamCooldowns = /* @__PURE__ */ new Map();
var DREAM_COOLDOWN_MS = 5 * 60 * 1e3;
function handleDreamMemoryStore(request, storeId) {
  return routeWrap(request, async ({ auth }) => {
    loadStoreForCaller(auth, storeId);
    const body = await request.json();
    const parsed = DreamRequestSchema.safeParse(body);
    if (!parsed.success) throw badRequest(parsed.error.message);
    const lastDreamed = dreamCooldowns.get(storeId);
    if (lastDreamed !== void 0 && Date.now() - lastDreamed < DREAM_COOLDOWN_MS) {
      const retryAfterSec = Math.ceil((DREAM_COOLDOWN_MS - (Date.now() - lastDreamed)) / 1e3);
      throw tooManyRequests(`dream was triggered recently; retry after ${retryAfterSec}s`);
    }
    const apiKey = parsed.data.api_key || getConfig().anthropicApiKey;
    if (!apiKey) {
      throw badRequest("No Anthropic API key available. Provide api_key in the request body or set ANTHROPIC_API_KEY.");
    }
    const result = await reviewSessions({
      storeId,
      lookbackMs: parsed.data.lookback_hours * 36e5,
      dryRun: parsed.data.dry_run,
      apiKey,
      model: parsed.data.model
    });
    dreamCooldowns.set(storeId, Date.now());
    return jsonOk({
      type: "dream_result",
      memory_store_id: storeId,
      session_count: result.sessionCount,
      proposed_changes: result.proposedChanges,
      applied: result.applied
    });
  });
}

export {
  handleCreateMemoryStore,
  handleListMemoryStores,
  handleGetMemoryStore,
  handleDeleteMemoryStore,
  handleUpdateMemoryStore,
  handleCreateMemory,
  handleListMemories,
  handleGetMemory,
  handleUpdateMemory,
  handleDeleteMemory,
  handleListMemoryVersions,
  handleGetMemoryVersion,
  handleRedactMemoryVersion,
  handleArchiveMemoryStore,
  handleDreamMemoryStore
};
