import {
  ensureSchema,
  getDashboardData,
  getRawDb,
  getUploadBucket,
  uid,
} from "../../../lib/mvp-db";
import { adminForbidden, isAdminRequest } from "../../../lib/admin-auth";
import { creatorScreenshotMcpUrl } from "../../../lib/creator-screenshot-access";
import {
  extractCreatorMetricsFromMcp,
  resolveCollectionMcpConfig,
  type CollectionMcpBindings,
} from "../../../lib/mcp-collection-client";
import { getRuntimeEnv } from "../../../lib/runtime-env";

export async function POST(request: Request) {
  if (!(await isAdminRequest(request))) return adminForbidden();
  try {
    await ensureSchema();
    const form = await request.formData();
    const distributionId = String(form.get("distributionId") ?? "");
    const file = form.get("file");
    if (!distributionId || !(file instanceof File) || file.size === 0) {
      return Response.json({ error: "请选择需要上传的截图" }, { status: 400 });
    }
    if (!file.type.startsWith("image/")) {
      return Response.json({ error: "只支持图片文件" }, { status: 400 });
    }
    const extension = file.name.split(".").at(-1)?.replace(/[^a-zA-Z0-9]/g, "") ||
      "jpg";
    const key = `creator-center/${distributionId}/${uid("shot")}.${extension}`;
    await getUploadBucket().put(key, await file.arrayBuffer(), {
      httpMetadata: { contentType: file.type },
    });
    const db = getRawDb();
    await db
      .prepare(
        `UPDATE distributions SET
          screenshot_key = ?,
          exposure = NULL,
          views = NULL,
          ocr_status = 'processing',
          updated_at = CURRENT_TIMESTAMP
         WHERE id = ?`,
      )
      .bind(key, distributionId)
      .run();
    try {
      const metrics = await extractCreatorMetricsFromMcp(
        creatorScreenshotMcpUrl(request, distributionId, key),
        resolveCollectionMcpConfig(getRuntimeEnv() as unknown as CollectionMcpBindings),
      );
      await db
        .prepare(
          `UPDATE distributions SET exposure = ?, views = ?,
             ocr_status = 'success', updated_at = CURRENT_TIMESTAMP
           WHERE id = ?`,
        )
        .bind(metrics.exposure, metrics.views, distributionId)
        .run();
    } catch (error) {
      console.error("[KOC LOOP] creator screenshot OCR failed", {
        distributionId,
        detail: error instanceof Error ? error.message : String(error),
      });
      await db
        .prepare(
          `UPDATE distributions SET ocr_status = 'failed', updated_at = CURRENT_TIMESTAMP WHERE id = ?`,
        )
        .bind(distributionId)
        .run();
    }
    return Response.json(await getDashboardData());
  } catch (error) {
    return Response.json(
      { error: error instanceof Error ? error.message : "上传失败" },
      { status: 500 },
    );
  }
}
