import { env } from "../../../env.js";
import { getLogger as getLogger$1 } from "../../../logger.js";
import manageDbClient_default from "../../../data/db/manageDbClient.js";
import { OpenAPIHono, z } from "@hono/zod-openapi";
import { createApiError, listAgentsAcrossProjectMainBranches, listUsableProjectIds, verifyTempToken } from "@inkeep/agents-core";
import { createProtectedRoute, inheritedAuth } from "@inkeep/agents-core/middleware";

//#region src/domains/manage/routes/availableAgents.ts
const logger = getLogger$1("availableAgents");
const app = new OpenAPIHono();
async function tryTempTokenAuth(token) {
	if (!env.INKEEP_AGENTS_TEMP_JWT_PUBLIC_KEY) return null;
	try {
		const payload = await verifyTempToken(Buffer.from(env.INKEEP_AGENTS_TEMP_JWT_PUBLIC_KEY, "base64").toString("utf-8"), token);
		return {
			userId: payload.sub,
			tenantId: payload.tenantId,
			tokenType: "temp-jwt"
		};
	} catch (error) {
		logger.warn({
			token,
			error
		}, "Failed to verify temp token");
		return null;
	}
}
/**
* Identify user from any supported token type
* Add new token types by adding them to this function
*/
async function identifyUserFromToken(token) {
	const tempResult = await tryTempTokenAuth(token);
	if (tempResult) return tempResult;
	return null;
}
const AvailableAgentSchema = z.object({
	agentId: z.string(),
	agentName: z.string(),
	projectId: z.string()
});
const AvailableAgentsResponseSchema = z.object({ data: z.array(AvailableAgentSchema) });
app.openapi(createProtectedRoute({
	method: "get",
	path: "/",
	summary: "List available agents",
	operationId: "list-available-agents",
	tags: ["Agents"],
	description: "List all agents the user can invoke. Requires a valid JWT token.",
	security: [{ bearerAuth: [] }],
	permission: inheritedAuth({ description: "Requires a valid JWT token (temp-jwt or work-app user token). Auth and SpiceDB authorization are enforced in the handler." }),
	responses: {
		200: {
			description: "List of available agents",
			content: { "application/json": { schema: AvailableAgentsResponseSchema } }
		},
		401: { description: "Unauthorized - invalid or missing JWT token" },
		500: { description: "Internal server error" }
	}
}), async (c) => {
	const authHeader = c.req.header("Authorization");
	if (!authHeader?.startsWith("Bearer ")) throw createApiError({
		code: "unauthorized",
		message: "Missing or invalid authorization header. Expected: Bearer <jwt_token>"
	});
	const token = authHeader.substring(7);
	if (!token.startsWith("eyJ")) throw createApiError({
		code: "unauthorized",
		message: "Invalid token format. Expected a JWT token."
	});
	const user = await identifyUserFromToken(token);
	if (!user) {
		logger.warn({}, "Token verification failed - no valid auth method found");
		throw createApiError({
			code: "unauthorized",
			message: "Invalid or expired token"
		});
	}
	const { userId, tenantId } = user;
	const projectIds = await listUsableProjectIds({
		userId,
		tenantId
	});
	if (projectIds.length === 0) return c.json({ data: [] });
	const agents = await listAgentsAcrossProjectMainBranches(manageDbClient_default, {
		tenantId,
		projectIds
	});
	logger.info({
		userId,
		tenantId,
		agentCount: agents.length
	}, "Returning usable agents");
	return c.json({ data: agents });
});
var availableAgents_default = app;

//#endregion
export { availableAgents_default as default };