import { NextResponse } from "next/server";
import { generateObject } from "../../lib/ai-sdk.js";
import { z } from "zod";
import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { llmProviderRegistry } from "@open-mercato/shared/lib/ai/llm-provider-registry";
import { resolveOpenCodeModel } from "@open-mercato/shared/lib/ai/opencode-provider";
import {
  resolveChatConfig,
  isProviderConfigured
} from "../../lib/chat-config.js";
import { createModelFactory, AiModelFactoryError } from "../../lib/model-factory.js";
const openApi = {
  tag: "AI Assistant",
  summary: "AI query routing",
  methods: {
    POST: { summary: "Route user query to appropriate AI handler" }
  }
};
const metadata = {
  POST: { requireAuth: true, requireFeatures: ["ai_assistant.view"] }
};
const RouteResultSchema = z.object({
  intent: z.enum(["tool", "general_chat"]),
  toolName: z.string().optional(),
  confidence: z.number().min(0).max(1),
  reasoning: z.string()
});
function createRoutingModel(providerId, configuredModel) {
  const provider = llmProviderRegistry.get(providerId);
  if (!provider) {
    throw new Error(`Unknown provider: ${providerId}`);
  }
  let modelId;
  let modelWithProvider;
  try {
    const resolved = resolveOpenCodeModel(providerId, {
      overrideModel: configuredModel
    });
    modelId = resolved.modelId;
    modelWithProvider = resolved.modelWithProvider;
  } catch {
    const requested = (configuredModel ?? "").trim();
    modelId = requested.length > 0 ? requested : provider.defaultModel;
    modelWithProvider = `${providerId}/${modelId}`;
  }
  const apiKey = provider.resolveApiKey();
  if (!apiKey) {
    const envKey = provider.getConfiguredEnvKey();
    throw new Error(`${envKey} not configured for provider "${providerId}"`);
  }
  const model = provider.createModel({ modelId, apiKey });
  return { model, modelWithProvider };
}
async function POST(req) {
  const auth = await getAuthFromRequest(req);
  if (!auth) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  try {
    const body = await req.json();
    const { query, availableTools } = body;
    console.log("[AI Route] Routing query:", query);
    console.log("[AI Route] Available tools count:", availableTools?.length);
    if (!query || typeof query !== "string") {
      return NextResponse.json({ error: "query is required" }, { status: 400 });
    }
    if (!availableTools || !Array.isArray(availableTools)) {
      return NextResponse.json({ error: "availableTools array is required" }, { status: 400 });
    }
    const container = await createRequestContainer();
    let config = await resolveChatConfig(container);
    if (!config) {
      let factoryResolution;
      try {
        factoryResolution = createModelFactory(container).resolveModel({
          callerOverride: void 0
        });
      } catch (error) {
        if (error instanceof AiModelFactoryError && error.code === "no_provider_configured") {
          return NextResponse.json(
            {
              error: "No AI provider configured. Please set an API key for one of the registered providers (Anthropic, OpenAI, Google, DeepInfra, Groq, \u2026)."
            },
            { status: 503 }
          );
        }
        throw error;
      }
      console.log("[AI Route] Using provider:", factoryResolution.providerId);
      const modelWithProvider2 = `${factoryResolution.providerId}/${factoryResolution.modelId}`;
      console.log("[AI Route] Calling generateObject with", modelWithProvider2);
      const result2 = await generateObject({
        model: factoryResolution.model,
        schema: RouteResultSchema,
        prompt: `You are a routing assistant. Given a user query, determine if they want to use a specific tool or have a general conversation.

Available tools:
${availableTools.map((t) => `- ${t.name}: ${t.description}`).join("\n")}

User query: "${query}"

Respond with:
- intent: "tool" if user wants to perform an action with a specific tool, "general_chat" otherwise
- toolName: the exact tool name if intent is "tool"
- confidence: 0-1 how confident you are
- reasoning: brief explanation`
      });
      console.log("[AI Route] Result:", result2.object);
      return NextResponse.json(result2.object);
    }
    console.log("[AI Route] Using provider:", config.providerId);
    if (!isProviderConfigured(config.providerId)) {
      return NextResponse.json(
        { error: `Configured provider ${config.providerId} is no longer available. Please update settings.` },
        { status: 503 }
      );
    }
    const { model, modelWithProvider } = createRoutingModel(config.providerId, config.model);
    const toolList = availableTools.map((t) => `- ${t.name}: ${t.description}`).join("\n");
    console.log("[AI Route] Calling generateObject with", modelWithProvider);
    const result = await generateObject({
      model,
      schema: RouteResultSchema,
      prompt: `You are a routing assistant. Given a user query, determine if they want to use a specific tool or have a general conversation.

Available tools:
${toolList}

User query: "${query}"

Respond with:
- intent: "tool" if user wants to perform an action with a specific tool, "general_chat" otherwise
- toolName: the exact tool name if intent is "tool"
- confidence: 0-1 how confident you are
- reasoning: brief explanation`
    });
    console.log("[AI Route] Result:", result.object);
    return NextResponse.json(result.object);
  } catch (error) {
    console.error("[AI Route] Error routing query:", error);
    return NextResponse.json(
      { error: "Routing request failed" },
      { status: 500 }
    );
  }
}
export {
  POST,
  metadata,
  openApi
};
//# sourceMappingURL=route.js.map
