// Scratch proof, not committed: the real fx status builder and registry merge, with only the
// `fx` CLI's answers faked (fx 0.0.13 output shapes).
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as ChildProcess from "effect/process/ChildProcess";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
import { ProviderInstanceId } from "@t3tools/contracts";
import { FxSettings } from "../../../../packages/provider-fx/src/settings.ts";
import { checkFxProviderStatus } from "../../../../packages/provider-fx/src/server/status.ts";
import * as ProviderRegistry from "./ProviderRegistry.ts";

const settings = Schema.decodeSync(FxSettings)({ enabled: true });
const encoder = new TextEncoder();
const handle = (stdout: string, code: number) =>
  ChildProcessSpawner.makeHandle({
    pid: ChildProcessSpawner.ProcessId(900_000_102),
    exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(code)),
    isRunning: Effect.succeed(false),
    kill: () => Effect.void,
    unref: Effect.succeed(Effect.void),
    stdin: Sink.drain,
    stdout: stdout ? Stream.succeed(encoder.encode(stdout)) : Stream.empty,
    stderr: Stream.empty,
    all: Stream.empty,
    getInputFd: () => Sink.drain,
    getOutputFd: () => Stream.empty,
  });
// `models` undefined makes `fx models --json` exit 2, like a failed listing.
const probe = (models: ReadonlyArray<string> | undefined) =>
  checkFxProviderStatus(settings, {}).pipe(
    Effect.provideService(
      ChildProcessSpawner.ChildProcessSpawner,
      ChildProcessSpawner.make((command) => {
        const args = ChildProcess.isStandardCommand(command) ? command.args.join(" ") : "";
        const outputs: Record<string, string | undefined> = {
          "--version": "fx 0.0.13\n",
          "status --json": JSON.stringify({ auth: "oauth" }),
          "models --json": models && JSON.stringify({ kind: "models", ids: models }),
        };
        const stdout = outputs[args];
        return Effect.succeed(handle(stdout ?? "", stdout === undefined ? 2 : 0));
      }),
    ),
    Effect.map((draft) => ({ ...draft, instanceId: ProviderInstanceId.make("fx") })),
  );

it.layer(NodeServices.layer)("fx runtime transcript", (it) => {
  it.effect("a model fx stops listing", () =>
    Effect.gen(function* () {
      const before = yield* probe(["anthropic/claude-sonnet-5.5", "openai/retired-model"]);
      const after = yield* probe(["anthropic/claude-sonnet-5.5"]);
      const failed = yield* probe(undefined);
      const line = (
        label: string,
        snapshot: { status: string; models: ReadonlyArray<{ slug: string }> },
      ) =>
        console.log(
          `${label.padEnd(40)} status=${snapshot.status.padEnd(7)} models=${JSON.stringify(snapshot.models.map((model) => model.slug))}`,
        );
      line("probe 1: fx lists retired-model", before);
      line("probe 2: fx no longer lists it", after);
      line("merged 1 -> 2 (what the picker shows)", ProviderRegistry.mergeProviderSnapshot(before, after));
      line("probe 3: fx models --json fails", failed);
      line("merged 1 -> 3 (what the picker shows)", ProviderRegistry.mergeProviderSnapshot(before, failed));
    }),
  );
});
