import {
  DEFAULT_TENANT_ID
} from "./chunk-X27B5TCC.js";
import {
  init_ids,
  newId
} from "./chunk-F4WUVOLE.js";
import {
  init_clock,
  nowMs,
  toIso
} from "./chunk-HFDLUBWN.js";
import {
  getDrizzle,
  init_drizzle
} from "./chunk-RII4M3J2.js";
import {
  schema_exports
} from "./chunk-DDJOPRB7.js";

// src/db/agents.ts
init_drizzle();
init_ids();
init_clock();
import { eq, and, isNull, lt, gt, asc, desc } from "drizzle-orm";
function hydrate(row, ver) {
  const modelConfig = ver.model_config_json ? JSON.parse(ver.model_config_json) : {};
  const rawMcp = ver.mcp_servers_json ? JSON.parse(ver.mcp_servers_json) : {};
  const mcpServers = Array.isArray(rawMcp) ? rawMcp : Object.entries(rawMcp).map(([name, cfg]) => ({
    name,
    type: "url",
    ...typeof cfg === "string" ? { url: cfg } : cfg
  }));
  const multiagent = ver.multiagent_json ? JSON.parse(ver.multiagent_json) : void 0;
  let threadsEnabled = Boolean(ver.threads_enabled);
  let callableAgents = ver.callable_agents_json ? JSON.parse(ver.callable_agents_json) : [];
  if (multiagent) {
    threadsEnabled = true;
    callableAgents = multiagent.agents.filter((a) => a.type === "agent").map((a) => ({ type: "agent", id: a.id, version: a.version }));
  }
  const permissionPolicy = ver.permission_policy_json ? JSON.parse(ver.permission_policy_json) : null;
  return {
    type: "agent",
    id: row.id,
    version: ver.version,
    name: row.name,
    description: row.description ?? "",
    model: { id: ver.model, ...modelConfig.speed ? { speed: modelConfig.speed } : {} },
    system: ver.system,
    tools: JSON.parse(ver.tools_json),
    mcp_servers: mcpServers,
    metadata: row.metadata_json ? JSON.parse(row.metadata_json) : {},
    engine: ver.backend ?? "claude",
    webhook_url: ver.webhook_url ?? null,
    webhook_events: ver.webhook_events_json ? JSON.parse(ver.webhook_events_json) : ["session.status_idle", "session.status_running", "session.error"],
    webhook_signing_enabled: ver.webhook_secret != null && ver.webhook_secret.length > 0,
    threads_enabled: threadsEnabled,
    confirmation_mode: Boolean(ver.confirmation_mode),
    callable_agents: callableAgents,
    multiagent,
    permission_policy: permissionPolicy,
    skills: ver.skills_json ? JSON.parse(ver.skills_json) : [],
    model_config: modelConfig,
    fallback_json: row.fallback_json ?? null,
    created_at: toIso(row.created_at),
    updated_at: toIso(row.updated_at),
    archived_at: row.archived_at ? new Date(row.archived_at).toISOString() : null
  };
}
function createAgent(input) {
  const db = getDrizzle();
  const id = newId("agent");
  const now = nowMs();
  db.transaction((tx) => {
    tx.insert(schema_exports.agents).values({
      id,
      current_version: 1,
      name: input.name,
      description: input.description ?? null,
      metadata_json: JSON.stringify(input.metadata ?? {}),
      tenant_id: input.tenant_id ?? DEFAULT_TENANT_ID,
      created_at: now,
      updated_at: now
    }).run();
    tx.insert(schema_exports.agentVersions).values({
      agent_id: id,
      version: 1,
      model: input.model,
      system: input.system ?? null,
      tools_json: JSON.stringify(input.tools ?? []),
      mcp_servers_json: JSON.stringify(input.mcp_servers ?? {}),
      backend: input.backend ?? "claude",
      webhook_url: input.webhook_url ?? null,
      webhook_events_json: JSON.stringify(input.webhook_events ?? ["session.status_idle", "session.status_running", "session.error"]),
      webhook_secret: input.webhook_secret ?? null,
      threads_enabled: input.threads_enabled ? 1 : 0,
      confirmation_mode: input.confirmation_mode ? 1 : 0,
      callable_agents_json: input.callable_agents?.length ? JSON.stringify(input.callable_agents) : null,
      multiagent_json: input.multiagent ? JSON.stringify(input.multiagent) : null,
      permission_policy_json: input.permission_policy ? JSON.stringify(input.permission_policy) : null,
      skills_json: JSON.stringify(input.skills ?? []),
      model_config_json: JSON.stringify(input.model_config ?? {}),
      created_at: now
    }).run();
  });
  return getAgent(id);
}
function getAgent(id, version) {
  const db = getDrizzle();
  const row = db.select().from(schema_exports.agents).where(eq(schema_exports.agents.id, id)).get();
  if (!row) return null;
  const v = version ?? row.current_version;
  const ver = db.select().from(schema_exports.agentVersions).where(
    and(
      eq(schema_exports.agentVersions.agent_id, id),
      eq(schema_exports.agentVersions.version, v)
    )
  ).get();
  if (!ver) return null;
  return hydrate(row, ver);
}
function updateAgent(id, input) {
  const db = getDrizzle();
  const existing = getAgent(id);
  if (!existing) return null;
  const existingVer = db.select({
    webhook_secret: schema_exports.agentVersions.webhook_secret,
    mcp_servers_json: schema_exports.agentVersions.mcp_servers_json
  }).from(schema_exports.agentVersions).where(
    and(
      eq(schema_exports.agentVersions.agent_id, id),
      eq(schema_exports.agentVersions.version, existing.version)
    )
  ).get();
  const carriedSecret = existingVer?.webhook_secret ?? null;
  const newVersion = existing.version + 1;
  const now = nowMs();
  db.transaction((tx) => {
    tx.insert(schema_exports.agentVersions).values({
      agent_id: id,
      version: newVersion,
      model: input.model ?? existing.model.id,
      system: input.system ?? existing.system,
      tools_json: JSON.stringify(input.tools ?? existing.tools),
      mcp_servers_json: input.mcp_servers ? JSON.stringify(input.mcp_servers) : existingVer?.mcp_servers_json ?? "{}",
      backend: existing.engine,
      webhook_url: input.webhook_url !== void 0 ? input.webhook_url : existing.webhook_url,
      webhook_events_json: JSON.stringify(input.webhook_events ?? existing.webhook_events),
      webhook_secret: input.webhook_secret !== void 0 ? input.webhook_secret : carriedSecret,
      threads_enabled: input.threads_enabled !== void 0 ? input.threads_enabled ? 1 : 0 : existing.threads_enabled ? 1 : 0,
      confirmation_mode: input.confirmation_mode !== void 0 ? input.confirmation_mode ? 1 : 0 : existing.confirmation_mode ? 1 : 0,
      callable_agents_json: input.callable_agents !== void 0 ? input.callable_agents.length ? JSON.stringify(input.callable_agents) : null : existing.callable_agents.length ? JSON.stringify(existing.callable_agents) : null,
      multiagent_json: input.multiagent !== void 0 ? input.multiagent ? JSON.stringify(input.multiagent) : null : existing.multiagent ? JSON.stringify(existing.multiagent) : null,
      permission_policy_json: input.permission_policy !== void 0 ? input.permission_policy ? JSON.stringify(input.permission_policy) : null : existing.permission_policy ? JSON.stringify(existing.permission_policy) : null,
      skills_json: JSON.stringify(input.skills ?? existing.skills),
      model_config_json: JSON.stringify(input.model_config !== void 0 ? input.model_config : existing.model_config),
      created_at: now
    }).run();
    tx.update(schema_exports.agents).set({
      current_version: newVersion,
      name: input.name ?? existing.name,
      description: input.description !== void 0 ? input.description ?? null : existing.description || null,
      metadata_json: input.metadata !== void 0 ? JSON.stringify(input.metadata) : JSON.stringify(existing.metadata),
      updated_at: now
    }).where(eq(schema_exports.agents.id, id)).run();
  });
  return getAgent(id);
}
function archiveAgent(id) {
  const db = getDrizzle();
  const res = db.update(schema_exports.agents).set({ archived_at: nowMs() }).where(and(eq(schema_exports.agents.id, id), isNull(schema_exports.agents.archived_at))).run();
  return res.changes > 0;
}
function listAgentVersions(agentId, opts) {
  const db = getDrizzle();
  const limit = Math.min(Math.max(opts.limit ?? 20, 1), 100);
  const row = db.select().from(schema_exports.agents).where(eq(schema_exports.agents.id, agentId)).get();
  if (!row) return [];
  const conditions = [eq(schema_exports.agentVersions.agent_id, agentId)];
  if (opts.cursor) {
    conditions.push(lt(schema_exports.agentVersions.version, opts.cursor));
  }
  const versions = db.select().from(schema_exports.agentVersions).where(and(...conditions)).orderBy(desc(schema_exports.agentVersions.version)).limit(limit).all();
  return versions.map((ver) => hydrate(row, ver));
}
function listAgents(opts) {
  const db = getDrizzle();
  const limit = Math.min(Math.max(opts.limit ?? 20, 1), 100);
  const orderDir = opts.order === "asc" ? "asc" : "desc";
  const includeArchived = opts.includeArchived ?? false;
  const conditions = [];
  if (!includeArchived) conditions.push(isNull(schema_exports.agents.archived_at));
  if (opts.cursor) {
    conditions.push(
      orderDir === "desc" ? lt(schema_exports.agents.id, opts.cursor) : gt(schema_exports.agents.id, opts.cursor)
    );
  }
  if (opts.tenantFilter != null) {
    conditions.push(eq(schema_exports.agents.tenant_id, opts.tenantFilter));
  }
  const where = conditions.length ? and(...conditions) : void 0;
  const orderClause = orderDir === "desc" ? desc(schema_exports.agents.id) : asc(schema_exports.agents.id);
  const rows = where ? db.select().from(schema_exports.agents).where(where).orderBy(orderClause).limit(limit).all() : db.select().from(schema_exports.agents).orderBy(orderClause).limit(limit).all();
  return rows.map((r) => getAgent(r.id)).filter(Boolean);
}

export {
  createAgent,
  getAgent,
  updateAgent,
  archiveAgent,
  listAgentVersions,
  listAgents
};
