/** 加载仓库 test/ 演示包到生成表单（经 AI /demo 接口）。 */
import { AI } from "./api";

export type DemoPack = {
  prompt: string;
  slug: string;
  excel: File | null;
  images: File[];
  layouts: File[];
  label: string;
  missing: string[];
};

async function fetchBlob(path: string): Promise<{ blob: Blob; name: string } | null> {
  const url = `${AI}/api/v1/demo/file/${path.split("/").map(encodeURIComponent).join("/")}`;
  const res = await fetch(url);
  if (!res.ok) return null;
  const blob = await res.blob();
  const name = path.split("/").pop() || "file";
  return { blob, name };
}

function toFile(blob: Blob, name: string, mime?: string): File {
  return new File([blob], name, { type: mime || blob.type || "application/octet-stream" });
}

export async function loadDemoFixtures(): Promise<DemoPack> {
  const missing: string[] = [];
  const metaRes = await fetch(`${AI}/api/v1/demo/fixtures`);
  if (!metaRes.ok) {
    throw new Error(`无法读取测试素材清单 HTTP ${metaRes.status}`);
  }
  const meta = await metaRes.json();
  if (!meta.available) {
    throw new Error(`测试目录不可用：${meta.root || "test/"}`);
  }

  const promptRes = await fetch(`${AI}/api/v1/demo/prompt`);
  const promptJson = await promptRes.json();
  const prompt = String(promptJson.prompt || "");
  if (!prompt) missing.push(meta.prompt || "prompt");

  const dataPath = meta.data || meta.files?.data?.path;
  let excel: File | null = null;
  if (dataPath) {
    const got = await fetchBlob(dataPath);
    if (got) {
      excel = toFile(got.blob, got.name, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    } else {
      missing.push(dataPath);
    }
  }

  const images: File[] = [];
  for (const p of meta.images || meta.files?.images?.map((x: any) => x.path) || []) {
    const got = await fetchBlob(p);
    if (got) images.push(toFile(got.blob, got.name, "image/png"));
    else missing.push(p);
  }

  const layouts: File[] = [];
  for (const p of meta.layouts || meta.files?.layouts?.map((x: any) => x.path) || []) {
    const got = await fetchBlob(p);
    if (got) layouts.push(toFile(got.blob, got.name, "text/html"));
    else missing.push(p);
  }

  return {
    prompt,
    slug: meta.slug || "settlement_observation_system",
    excel,
    images,
    layouts,
    label: meta.label || "演示包",
    missing,
  };
}
