/**
 * product-image-three-views
 * 基于一张参考图生成商品的三视图（正视图 / 侧视图 / 俯视图）。
 * 仅 lovable provider（gemini-2.5-flash-image）支持图生图。
 *
 * Body: { name?: string; description?: string; referenceImage: string  http(s) URL ; }
 * Resp: { views: { view: 'front'|'side'|'top'; label: string; url: string; path: string }[] }
 */
import { createClient } from "https://esm.sh/@supabase/supabase-js@2.45.0";
import { corsHeaders, handlePreflight } from "../_shared/cors.ts";
import { generateImage, base64ToBytes } 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" },
  });
}

const VIEW_PROMPTS: Array<{ key: "front" | "side" | "top"; label: string; instruction: string }> = [
  {
    key: "front",
    label: "正视图",
    instruction:
      "Generate the FRONT view (elevation) of this exact product, camera directly facing the product at eye level, head-on perspective, fully showing the front face.",
  },
  {
    key: "side",
    label: "侧视图",
    instruction:
      "Generate the SIDE view (profile) of this exact product, camera at 90 degrees to the front, perfectly perpendicular side profile, fully showing one side face.",
  },
  {
    key: "top",
    label: "俯视图",
    instruction:
      "Generate the TOP-DOWN view (plan view) of this exact product, camera looking straight down from directly above (90 degrees overhead), fully showing the top face.",
  },
];

function buildViewPrompt(
  view: typeof VIEW_PROMPTS[number],
  name?: string,
  description?: string,
) {
  const subject = name ? `the product "${name}"` : "the product in the reference image";
  return [
    `You are given a reference photograph of a product. Use it as the visual ground truth for shape, proportion, color, material and details.`,
    description ? `Additional product details: ${description}.` : "",
    view.instruction.replace("this exact product", subject),
    "Maintain the IDENTICAL product identity (same shape, color, material, branding) as the reference image — do not invent a different object.",
    "Studio lighting, clean pure white seamless background, centered composition, subtle soft shadow, true-to-life colors.",
    "High resolution, sharp focus, no text, no watermark, no people, no extra props, single product only.",
  ].filter(Boolean).join(" ");
}

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

  try {
    const { name, description, referenceImage } = await req.json().catch(() => ({}));
    if (!referenceImage || typeof referenceImage !== "string") {
      return json({ error: "referenceImage 必填（参考图 URL）" }, 400);
    }

    // 鉴权
    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);

    // 并行生成三视图（使用独立的 product_image_three_views 配置）
    const tasks = VIEW_PROMPTS.map((v) =>
      generateImage("product_image_three_views", {
        prompt: buildViewPrompt(v, name, description),
        referenceImages: [referenceImage],
      }).then((img) => ({ v, img }))
        .catch((e) => ({ v, error: e?.message ?? String(e) } as any)),
    );
    const results = await Promise.all(tasks);

    // 上传成功的视图
    const admin = createClient(SUPABASE_URL, SERVICE_ROLE);
    const views: Array<{ view: string; label: string; url: string; path: string }> = [];
    const errors: Array<{ view: string; label: string; error: string }> = [];

    for (const r of results) {
      if ((r as any).error || !(r as any).img) {
        errors.push({ view: r.v.key, label: r.v.label, error: (r as any).error || "生成失败" });
        continue;
      }
      const img = (r as any).img;
      const ext = (img.mime.split("/")[1] || "png").replace("jpeg", "jpg");
      const bytes = base64ToBytes(img.base64);
      const path = `products/views/${r.v.key}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}.${ext}`;
      const { error: upErr } = await admin.storage
        .from("product-images")
        .upload(path, bytes, { contentType: img.mime, upsert: false });
      if (upErr) {
        errors.push({ view: r.v.key, label: r.v.label, error: upErr.message });
        continue;
      }
      const { data: pub } = admin.storage.from("product-images").getPublicUrl(path);
      views.push({ view: r.v.key, label: r.v.label, url: pub.publicUrl, path });
    }

    if (views.length === 0) {
      return json({ error: "三视图全部生成失败", errors }, 500);
    }

    return json({ views, errors });
  } catch (e: any) {
    console.error("product-image-three-views error", e);
    const status = e?.status ?? 500;
    return json({ error: e?.message ?? String(e), code: e?.code }, status);
  }
});
