import {
  jsonOk,
  routeWrap
} from "./chunk-KKJ5D3II.js";
import {
  badRequest,
  notFound
} from "./chunk-EZYKRG4W.js";

// src/handlers/google-compat/agents.ts
import { z } from "zod";
var SourceSchema = z.object({
  type: z.string().optional(),
  target: z.string().optional(),
  content: z.string().optional(),
  url: z.string().optional()
}).passthrough();
var BaseEnvironmentSchema = z.object({
  type: z.string().optional(),
  sources: z.array(SourceSchema).optional()
}).passthrough();
var CreateGoogleAgentSchema = z.object({
  id: z.string().optional(),
  description: z.string().optional(),
  base_agent: z.string().optional(),
  system_instruction: z.string().optional(),
  tools: z.array(z.unknown()).optional(),
  base_environment: BaseEnvironmentSchema.optional()
});
function resolveBaseAgent(baseAgent) {
  if (!baseAgent) return { engine: "gemini", model: "gemini-2.5-flash" };
  if (baseAgent === "antigravity-preview-05-2026") {
    return { engine: "gemini", model: "gemini-2.5-flash" };
  }
  return { engine: "gemini", model: baseAgent };
}
function toGoogleFormat(agent) {
  return {
    id: agent.name,
    base_agent: agent.engine === "gemini" ? "antigravity-preview-05-2026" : void 0,
    system_instruction: agent.system ?? void 0,
    description: agent.description ?? void 0,
    created: agent.created_at ?? (/* @__PURE__ */ new Date()).toISOString(),
    updated: agent.updated_at ?? agent.created_at ?? (/* @__PURE__ */ new Date()).toISOString()
  };
}
function handleCreateGoogleAgent(request) {
  return routeWrap(request, async () => {
    const body = await request.json().catch(() => null);
    const parsed = CreateGoogleAgentSchema.safeParse(body);
    if (!parsed.success) {
      throw badRequest(`invalid body: ${parsed.error.issues.map((i) => i.message).join("; ")}`);
    }
    const data = parsed.data;
    const { engine, model } = resolveBaseAgent(data.base_agent);
    let systemInstruction = data.system_instruction ?? "";
    const skills = [];
    if (data.base_environment?.sources) {
      for (const source of data.base_environment.sources) {
        const target = source.target ?? "";
        const skillMatch = target.match(/\.agents\/skills\/([^/]+)\/SKILL\.md$/);
        if (skillMatch && source.content) {
          skills.push({
            name: skillMatch[1],
            source: "inline",
            content: source.content
          });
        } else if (target.endsWith(".agents/AGENTS.md") && source.content) {
          if (systemInstruction) systemInstruction += "\n\n";
          systemInstruction += source.content;
        }
      }
    }
    const agentName = data.id || `google-agent-${Date.now()}`;
    const { handleCreateAgent } = await import("./handlers/anthropic-compat/agents.js");
    const createBody = {
      name: agentName,
      model: { id: model },
      engine
    };
    if (systemInstruction) createBody.system = systemInstruction;
    if (data.description) createBody.description = data.description;
    if (skills.length > 0) createBody.skills = skills;
    const createReq = new Request(request.url.replace(/\/google\/v1beta\/agents.*/, `/v1/agents`), {
      method: "POST",
      headers: request.headers,
      body: JSON.stringify(createBody)
    });
    const createRes = await handleCreateAgent(createReq);
    if (!createRes.ok) {
      const err = await createRes.json().catch(() => ({}));
      throw badRequest(err.error?.message || `failed to create agent: ${createRes.status}`);
    }
    const created = await createRes.json();
    const response = {
      id: created.name ?? agentName,
      base_agent: data.base_agent,
      system_instruction: systemInstruction || void 0,
      description: data.description,
      created: created.created_at ?? (/* @__PURE__ */ new Date()).toISOString(),
      updated: created.updated_at ?? created.created_at ?? (/* @__PURE__ */ new Date()).toISOString()
    };
    return jsonOk(response, 201);
  });
}
function handleListGoogleAgents(request) {
  return routeWrap(request, async () => {
    const { handleListAgents } = await import("./handlers/anthropic-compat/agents.js");
    const listReq = new Request(request.url.replace(/\/google\/v1beta\/agents.*/, `/v1/agents?limit=1000`), {
      headers: request.headers
    });
    const listRes = await handleListAgents(listReq);
    if (!listRes.ok) {
      return listRes;
    }
    const listBody = await listRes.json();
    const agents = (listBody.data ?? []).map(toGoogleFormat);
    return jsonOk({ agents });
  });
}
function handleGetGoogleAgent(request, id) {
  return routeWrap(request, async () => {
    const { handleListAgents } = await import("./handlers/anthropic-compat/agents.js");
    const listReq = new Request(request.url.replace(/\/google\/v1beta\/agents.*/, `/v1/agents?limit=1000`), {
      headers: request.headers
    });
    const listRes = await handleListAgents(listReq);
    if (!listRes.ok) {
      return listRes;
    }
    const listBody = await listRes.json();
    const agent = listBody.data?.find((a) => a.name === id);
    if (!agent) throw notFound(`agent not found: ${id}`);
    return jsonOk(toGoogleFormat(agent));
  });
}
function handleDeleteGoogleAgent(request, id) {
  return routeWrap(request, async () => {
    const { handleListAgents, handleDeleteAgent } = await import("./handlers/anthropic-compat/agents.js");
    const listReq = new Request(request.url.replace(/\/google\/v1beta\/agents.*/, `/v1/agents?limit=1000`), {
      headers: request.headers
    });
    const listRes = await handleListAgents(listReq);
    if (!listRes.ok) {
      return listRes;
    }
    const listBody = await listRes.json();
    const agent = listBody.data?.find((a) => a.name === id);
    if (!agent) throw notFound(`agent not found: ${id}`);
    const delReq = new Request(request.url.replace(/\/google\/v1beta\/agents.*/, `/v1/agents/${agent.id}`), {
      method: "DELETE",
      headers: request.headers
    });
    await handleDeleteAgent(delReq, agent.id);
    return jsonOk({});
  });
}

export {
  handleCreateGoogleAgent,
  handleListGoogleAgents,
  handleGetGoogleAgent,
  handleDeleteGoogleAgent
};
