#!/usr/bin/env bun
// SPEC: issue-1190 fake Responses provider P0/P1.
// Responsibility: Bun entrypoint for the deterministic fake Responses provider.
import { createFakeResponsesProviderService, loadFakeResponsesProviderConfig } from "./src/fake-responses-provider-service";

const args = process.argv.slice(2);
const config = loadFakeResponsesProviderConfig({
  ...process.env,
  ...(optionValue("--host") === undefined ? {} : { LISTEN_HOST: optionValue("--host") }),
  ...(optionValue("--port") === undefined ? {} : { PORT: optionValue("--port") }),
  ...(optionValue("--model") === undefined ? {} : { FAKE_RESPONSES_MODEL_ID: optionValue("--model") }),
});
const service = createFakeResponsesProviderService(config);

if (args.includes("--once")) {
  console.log(JSON.stringify(service.health(), null, 2));
  process.exit(0);
}

const server = Bun.serve({
  hostname: config.host,
  port: config.port,
  fetch: service.fetch,
});

console.log(JSON.stringify({
  ok: true,
  command: "fake-responses-provider-service",
  url: server.url.href,
  health: service.health(),
  valuesPrinted: false,
}, null, 2));

process.on("SIGTERM", () => {
  server.stop(true);
  process.exit(0);
});
process.on("SIGINT", () => {
  server.stop(true);
  process.exit(0);
});

await new Promise(() => undefined);

function optionValue(name: string): string | undefined {
  const index = args.indexOf(name);
  if (index === -1) return undefined;
  const value = args[index + 1];
  if (value === undefined || value.startsWith("--")) throw new Error(`${name} requires a value`);
  return value;
}
