/**
 * product-video-generate
 * 通过统一 AI Provider 适配层生成商品视频，上传到 Storage 返回公开 URL。
 * Provider/模型由 ai_provider_configs 表的 purpose='product_video' 行控制（仅支持通义万相）。
 *
 * Body: {
 *   name: string;
 *   description?: string;
 *   extraPrompt?: string;
 *   referenceImage?: string;   // 可选；提供则触发图生视频
 *   duration?: 5 | 10;          // 视频时长，默认 5 秒
 *   aspectRatio?: '16:9' | '9:16' | '1:1'; // 默认 16:9
 * }
 * Resp: { url: string; path: string; provider: string; model: string }
 */
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.45.0";
import { corsHeaders, handlePreflight } from "../_shared/cors.ts";
import { generateVideo, loadProviderConfig } from "../_shared/aiProvider.ts";

const SUPABASE_URL = Deno.env.get("SUPABASE_URL")!;
const SERVICE_ROLE = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY")!;

function json(data: unknown, status = 200) {
  return new Response(JSON.stringify(data), {
    status,
    headers: { ...corsHeaders, "Content-Type": "application/json" },
  });
}

function aspectToSize(ratio?: string): string {
  switch (ratio) {
    case "9:16": return "720*1280";
    case "1:1": return "960*960";
    case "16:9":
    default: return "1280*720";
  }
}

function buildPrompt(
  name: string,
  description: string | undefined,
  extra: string | undefined,
  hasRef: boolean,
) {
  const intro = hasRef
    ? `Animate the reference product image into a short cinematic e-commerce showcase of "${name}".`
    : `Create a short cinematic e-commerce product showcase video of "${name}".`;
  return [
    intro,
    description ? `Product details: ${description}.` : "",
    "Smooth slow camera motion (subtle dolly / orbit / push-in), studio lighting, clean background, true-to-life materials and colors.",
    "Keep the product as the single focal subject, no people, no text overlays, no logos other than what's on the product, no watermark.",
    extra || "",
  ].filter(Boolean).join(" ");
}

Deno.serve(async (req) => {
  const pre = handlePreflight(req);
  if (pre) return pre;

  try {
    const body = await req.json().catch(() => ({}));
    const { name, description, extraPrompt, referenceImage, duration, aspectRatio } = body || {};
    if (!name || typeof name !== "string") return json({ error: "name 必填" }, 400);

    const dur: 5 | 10 = duration === 10 ? 10 : 5;

    // 鉴权
    const authHeader = req.headers.get("Authorization") ?? "";
    const userClient = createClient(SUPABASE_URL, SERVICE_ROLE, {
      global: { headers: { Authorization: authHeader } },
    });
    const { data: userData } = await userClient.auth.getUser();
    if (!userData?.user) return json({ error: "未登录" }, 401);

    const cfg = await loadProviderConfig("product_video");
    const prompt = buildPrompt(name, description, extraPrompt, !!referenceImage);

    const video = await generateVideo("product_video", {
      prompt,
      referenceImage: referenceImage || undefined,
      duration: dur,
      size: aspectToSize(aspectRatio),
    });

    const admin = createClient(SUPABASE_URL, SERVICE_ROLE);
    const ext = (video.mime.split("/")[1] || "mp4").split(";")[0];
    const path = `videos/ai_${Date.now()}_${Math.random().toString(36).slice(2, 8)}.${ext}`;
    const { error: upErr } = await admin.storage
      .from("product-images")
      .upload(path, video.bytes, { contentType: video.mime, upsert: false });
    if (upErr) {
      console.error("upload error", upErr);
      return json({ error: "视频上传失败：" + upErr.message }, 500);
    }
    const { data: pub } = admin.storage.from("product-images").getPublicUrl(path);

    return json({ url: pub.publicUrl, path, provider: cfg.provider, model: cfg.model });
  } catch (e: any) {
    console.error("product-video-generate error", e);
    const status = e?.status ?? 500;
    return json({ error: e?.message ?? String(e), code: e?.code }, status);
  }
});
