import {
  createSession
} from "./chunk-SEGKFEG5.js";
import {
  createEnvironment,
  deleteEnvironment,
  getEnvironment
} from "./chunk-GTYDSYTR.js";
import {
  archiveAgent,
  createAgent,
  getAgent
} from "./chunk-LGPJPAHU.js";
import {
  getDrizzle,
  init_drizzle
} from "./chunk-RII4M3J2.js";

// src/db/batch.ts
init_drizzle();
function executeBatch(operations) {
  const db = getDrizzle();
  return db.transaction(() => {
    const results = [];
    for (const op of operations) {
      try {
        const result = executeSingleOp(op);
        results.push(result);
      } catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        throw new BatchError(results.length, msg, results);
      }
    }
    return results;
  });
}
var BatchError = class extends Error {
  constructor(failedIndex, message, partialResults) {
    super(message);
    this.failedIndex = failedIndex;
    this.partialResults = partialResults;
    this.name = "BatchError";
  }
  failedIndex;
  partialResults;
};
function executeSingleOp(op) {
  const { method, path, body } = op;
  const upperMethod = method.toUpperCase();
  if (upperMethod === "POST" && path === "/anthropic/v1/agents") {
    if (!body?.name || !body?.model) {
      throw new Error("agent creation requires name and model");
    }
    const agent = createAgent({
      name: body.name,
      model: body.model,
      system: body.system ?? null,
      tools: body.tools ?? [],
      mcp_servers: body.mcp_servers ?? {},
      backend: body.backend ?? "claude",
      webhook_url: body.webhook_url ?? null,
      webhook_events: body.webhook_events,
      threads_enabled: body.threads_enabled ?? false
    });
    return { status: 201, body: agent };
  }
  if (upperMethod === "POST" && path === "/anthropic/v1/environments") {
    if (!body?.name || !body?.config) {
      throw new Error("environment creation requires name and config");
    }
    const env = createEnvironment({
      name: body.name,
      config: body.config
    });
    return { status: 201, body: env };
  }
  if (upperMethod === "POST" && path === "/anthropic/v1/sessions") {
    if (!body?.agent || !body?.environment_id) {
      throw new Error("session creation requires agent and environment_id");
    }
    const agentRef = body.agent;
    const agentId = typeof agentRef === "string" ? agentRef : agentRef.id;
    const agentVersion = typeof agentRef === "string" ? void 0 : agentRef.version;
    const agent = getAgent(agentId, agentVersion);
    if (!agent) throw new Error(`agent not found: ${agentId}`);
    const env = getEnvironment(body.environment_id);
    if (!env) throw new Error(`environment not found: ${body.environment_id}`);
    const session = createSession({
      agent_id: agent.id,
      agent_version: agent.version,
      environment_id: env.id,
      title: body.title ?? null,
      metadata: body.metadata ?? {},
      max_budget_usd: body.max_budget_usd ?? null,
      vault_ids: body.vault_ids ?? null
    });
    return { status: 201, body: session };
  }
  const agentDeleteMatch = path.match(/^\/anthropic\/v1\/agents\/([^/]+)$/);
  if (upperMethod === "DELETE" && agentDeleteMatch) {
    const id = agentDeleteMatch[1];
    const archived = archiveAgent(id);
    if (!archived) throw new Error(`agent not found: ${id}`);
    return { status: 200, body: { id, type: "agent_deleted" } };
  }
  const envDeleteMatch = path.match(/^\/anthropic\/v1\/environments\/([^/]+)$/);
  if (upperMethod === "DELETE" && envDeleteMatch) {
    const id = envDeleteMatch[1];
    const deleted = deleteEnvironment(id);
    if (!deleted) throw new Error(`environment not found: ${id}`);
    return { status: 200, body: { id, type: "environment_deleted" } };
  }
  throw new Error(`unsupported batch operation: ${method} ${path}`);
}

export {
  executeBatch,
  BatchError
};
