import { NextResponse } from "next/server";
import { prisma, resolvePersona } from "@/lib/db";
import { getActiveAccountProfile } from "@/lib/account-context";
import { getOrCreateSettings } from "@/lib/user-settings";
import { refineResearchMap, type RefineChatMessage } from "@/lib/ai/refine-research-map";
import { parseProviderApiKeys } from "@/lib/ai/keys";
import type { ResearchMap } from "@/lib/types/research";
import { trackAiTask } from "@/lib/jobs/track";

export const maxDuration = 120;

export async function POST(request: Request) {
  try {
    const body = (await request.json()) as {
      topicId?: string;
      researchMap?: ResearchMap;
      message?: string;
      history?: RefineChatMessage[];
    };

    const { topicId, researchMap, message, history } = body;

    if (!topicId || !researchMap || !message?.trim()) {
      return NextResponse.json(
        { error: "缺少 topicId、researchMap 或 message" },
        { status: 400 }
      );
    }

    const topic = await prisma.topic.findUnique({ where: { id: topicId } });
    if (!topic) {
      return NextResponse.json({ error: "找不到主題" }, { status: 404 });
    }

    const settings = await getOrCreateSettings();
    const account = await getActiveAccountProfile();
    const apiKeys = parseProviderApiKeys(settings.providerApiKeys);

    const result = await trackAiTask("微調研究地圖", () => refineResearchMap({
      label: topic.label,
      query: topic.query,
      brief: topic.brief,
      persona: resolvePersona(settings, account),
      currentMap: researchMap,
      message: message.trim(),
      history: history ?? [],
      aiProvider: settings.researchAiProvider ?? settings.aiProvider,
      aiModel: settings.researchAiModel ?? settings.aiModel,
      apiKeys,
    }));

    return NextResponse.json(result);
  } catch (error) {
    const msg = error instanceof Error ? error.message : "微調失敗";
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
