import { describe, expect, it, vi } from "vitest";

import type { GenerationAdapterRequest } from "../../apps/worker/src/ai-adapter-contract.js";
import { runAiRuntimeProbe } from "../../apps/worker/src/ai-runtime-probe.js";
import { OneApiGenerationAdapter } from "../../apps/worker/src/oneapi-generation-adapter.js";

function request(overrides: Partial<GenerationAdapterRequest> = {}): GenerationAdapterRequest {
  return {
    configSnapshot: {},
    generationId: "00000000-0000-4000-8000-000000000001",
    modelId: "gemini-3.1-flash-image-preview",
    prompt: "一张用于本机验收的抽象色彩图",
    ratio: "1:1",
    referenceAssetIds: [],
    ...overrides,
  };
}

describe("POSTV1-02 OneAPI runtime adapter", () => {
  it("uses the fixed Gemini gateway and normalizes one real-shaped response", async () => {
    const source = Buffer.from(
      "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=",
      "base64",
    );
    const gateway = vi.fn(async (_url: string | URL | Request, init?: RequestInit) => {
      const headers = new Headers(init?.headers);
      expect(headers.get("authorization")).toBe("Bearer synthetic-runtime-token");
      expect(init?.redirect).toBe("error");
      const payload = JSON.parse(String(init?.body)) as { messages: Array<{ content: unknown; role: string }> };
      expect(payload.messages).toEqual([
        {
          content: "Generate exactly one image from the user's description. Return the generated image and do not answer with text only.",
          role: "system",
        },
        { content: "一张用于本机验收的抽象色彩图", role: "user" },
      ]);
      return new Response(JSON.stringify({
        choices: [{ message: { content: `![result](data:image/png;base64,${source.toString("base64")})` } }],
      }), { headers: { "content-type": "application/json" }, status: 200 });
    });
    const credential = Buffer.from("synthetic-runtime-token");
    const adapter = new OneApiGenerationAdapter({ credential, fetch: gateway as typeof fetch });
    const result = await adapter.start(request());

    expect(gateway).toHaveBeenCalledOnce();
    expect(gateway.mock.calls[0]?.[0]).toBe("https://oneapi.intelligrow.cn/v1/chat/completions");
    expect(result.status === "failed" ? result.sourceCategory : "completed").toBe("completed");
    if (result.status === "completed") {
      expect(result.outputs).toHaveLength(1);
      expect(result.outputs[0]).toMatchObject({ mimeType: "image/png", pixelHeight: 1080, pixelWidth: 1080 });
      expect(result.outputs[0]?.bytes.length).toBeGreaterThan(0);
    }
    expect(JSON.stringify(result)).not.toContain("synthetic-runtime-token");
    adapter.dispose();
    credential.fill(0);
  });

  it("fails closed instead of returning a mock image", async () => {
    const adapter = new OneApiGenerationAdapter({
      credential: Buffer.from("synthetic-runtime-token"),
      fetch: vi.fn(async () => new Response(null, { status: 503 })) as typeof fetch,
    });
    await expect(adapter.start(request())).resolves.toEqual({
      category: "upstream_failed",
      sourceCategory: "upstream_http_503",
      status: "failed",
    });
    adapter.dispose();
    await expect(adapter.start(request())).resolves.toEqual({
      category: "upstream_failed",
      sourceCategory: "adapter_disposed",
      status: "failed",
    });
  });

  it("returns only a bounded probe summary and wipes generated bytes", async () => {
    const bytes = Buffer.from("probe-output");
    const result = await runAiRuntimeProbe({
      async start() {
        return { outputs: [{ bytes, mimeType: "image/png", pixelHeight: 1080, pixelWidth: 1080 }], status: "completed" };
      },
    });
    expect(result).toEqual({
      code: "ai_probe_passed",
      mime_type: "image/png",
      pixel_height: 1080,
      pixel_width: 1080,
      real_calls: 1,
      success: true,
    });
    expect(bytes.every((value) => value === 0)).toBe(true);
  });
});
