import { errorResponses, safeGetJsonBody, validateRequestBody } from "@/lib/api-utils";
import { isConvexEnabled } from "@/lib/convex/enabled";
import { getAuthedConvexClient } from "@/lib/convex/route";
import {
  startMnoteCliAgentHostRun,
  type MnoteCliAgentRunPayload,
} from "@/lib/server/mnote-cli-agent-host";
import { NextResponse } from "next/server";

export const dynamic = "force-dynamic";

export async function POST(request: Request) {
  const payload = await safeGetJsonBody<MnoteCliAgentRunPayload>(request);
  if (!payload) {
    return errorResponses.badRequest("请求体不能为空");
  }
  const validationError = validateRequestBody(payload, ["messages"] as const);
  if (validationError) return validationError;
  if (!Array.isArray(payload.messages) || payload.messages.length === 0) {
    return errorResponses.badRequest("缺少 messages");
  }

  let userId = "";
  let userEmail: string | undefined;
  let userName: string | undefined;
  if (isConvexEnabled()) {
    const { auth } = await getAuthedConvexClient();
    userId = auth.userId ?? "";
    userEmail = auth.email;
    userName = auth.name;
  }
  if (!userId) {
    return errorResponses.unauthorized();
  }

  const provider = String(payload.options?.ai?.provider ?? "").trim().toLowerCase();
  if (provider === "codex" || provider === "hermes" || provider === "claudecode") {
    return NextResponse.json(
      {
        error: `${provider} 已退出默认系统组件，当前只保留 mnote-cli host 主执行入口。`,
      },
      {
        status: 410,
        headers: {
          "x-mnote-ai-execution-owner": `${provider}-retired`,
        },
      },
    );
  }

  return startMnoteCliAgentHostRun({
    request,
    userId,
    userEmail,
    userName,
    payload,
  });
}
