import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";

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

import { createApp } from "../../apps/api/src/app.js";
import { ModelConfigurationService } from "../../apps/api/src/model-configuration.js";
import { RegistrationService } from "../../apps/api/src/registration.js";
import { MockResendAdapter } from "../../apps/api/src/resend-adapter.js";

const roots: string[] = [];
const services: RegistrationService[] = [];
const now = Date.parse("2026-08-02T15:00:00.000Z");
const headers = { host: "127.0.0.1:43121", origin: "http://127.0.0.1:43121" };

afterEach(() => {
  for (const service of services.splice(0)) service.close();
  for (const root of roots.splice(0)) rmSync(root, { force: true, recursive: true });
});

describe("TASK-WP3-02 model runtime API", () => {
  it("returns recommended separately from configured default as runtime changes", async () => {
    const root = mkdtempSync(join(tmpdir(), "dada-wp3-02-api-"));
    roots.push(root);
    const registration = new RegistrationService({
      challengePepper: Buffer.alloc(32, 0x91), clock: () => now,
      currentPrivacyNoticeVersion: "p0a-registration-notice-v1", databasePath: join(root, "dada.sqlite3"),
      invitePepper: Buffer.alloc(32, 0x92), resend: new MockResendAdapter(), sessionPepper: Buffer.alloc(32, 0x93),
    });
    services.push(registration);
    const models = new ModelConfigurationService({ database: registration.database, clock: () => now });
    const candidates = structuredClone(models.read().models);
    for (const candidate of candidates) {
      candidate.contract_validation_status = "verified";
      candidate.contract_evidence_ref = `fixture-${candidate.model_id}`;
    }
    models.replace({ actorId: "wp3-02-api", expectedConfigSetVersion: 1, idempotencyKey: "wp3-02-api-verified-00000000000000000001", models: candidates });
    registration.database.prepare("UPDATE model_runtime_availability SET available_for_new_jobs = 1, reason = 'available', checked_at = ?").run(now);
    const app = await createApp({ browserGate: false, models, networkBoundary: { allowTestPort: true }, registration });
    const available = await app.inject({ headers, method: "GET", url: "/api/v1/models" });
    expect(available.statusCode).toBe(200);
    expect(available.json()).toMatchObject({ configured_default_model_id: "gemini-3.1-flash-image-preview", recommended_model_id: "gemini-3.1-flash-image-preview" });
    registration.database.prepare("UPDATE model_runtime_availability SET available_for_new_jobs = 0, reason = 'gateway_balance_insufficient', runtime_availability_version = runtime_availability_version + 1 WHERE model_id = ?")
      .run("gemini-3.1-flash-image-preview");
    const blocked = await app.inject({ headers, method: "GET", url: "/api/v1/models" });
    expect(blocked.json()).toMatchObject({ configured_default_model_id: "gemini-3.1-flash-image-preview", recommended_model_id: "gemini-3-pro-image-preview" });
    await app.close();
  });
});
