import { prisma, resolvePersona } from "@/lib/db";
import { getOrCreateSettings } from "@/lib/user-settings";
import { getActiveAccountProfile } from "@/lib/account-context";
import { generatePostDrafts } from "@/lib/ai/generate-posts";
import { parseProviderApiKeys } from "@/lib/ai/keys";

export async function generateDraftsForScan(scanId: string) {
  const scan = await prisma.scan.findUnique({
    where: { id: scanId },
    include: {
      topic: true,
      items: {
        where: { OR: [{ qualityTier: null }, { qualityTier: { not: "EXCLUDE" } }] },
        orderBy: [{ combinedScore: "desc" }, { score: "desc" }],
        take: 8,
        include: {
          replies: { orderBy: { likeCount: "desc" }, take: 5 },
        },
      },
    },
  });

  if (!scan) throw new Error("找不到海巡紀錄");
  if (scan.items.length === 0) throw new Error("此海巡沒有素材，請重新海巡");

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

  const drafts = await generatePostDrafts({
    topicLabel: scan.topic.label,
    persona: resolvePersona(settings, account),
    aiProvider: settings.aiProvider,
    aiModel: settings.aiModel,
    apiKeys,
    count: settings.draftsPerScan,
    posts: scan.items.map((item) => ({
      text: item.text,
      authorName: item.authorName,
      permalink: item.permalink,
      likeCount: item.likeCount,
      replyCount: item.replyCount,
      replies: item.replies.map((r) => ({
        text: r.text,
        authorName: r.authorName,
        likeCount: r.likeCount,
      })),
    })),
  });

  const created = [];
  for (const draft of drafts) {
    const record = await prisma.draft.create({
      data: {
        accountId: scan.topic.accountId,
        topicId: scan.topicId,
        text: draft.text,
        angle: draft.angle,
        rationale: draft.rationale,
        sources: JSON.stringify(draft.sourcePermalinks),
        status: "PENDING",
      },
    });
    created.push(record);
  }

  return created;
}
