import * as FS from "node:fs";
import * as Path from "node:path";
import { pathToFileURL } from "node:url";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { CommandId, ThreadId, ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { withThreadTools } from "../../apps/server/src/cli/thread.ts";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NetService from "@t3tools/shared/Net";
import { GlobalFlag } from "effect/cli";
import * as Option from "effect/Option";
import { OrchestratorMcpThreadInterruptResult } from "@t3tools/contracts";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { test, WEB, rpcClient, runPromise, makeState } from "./t3.ts";

test("Provider defaults translate and custom agent stops stay verbatim", WEB, async ({ t3, app, screen }) => {
  // Reuse the app's Replay engine with an existing live FX recording, unchanged.
  const recorded = pathToFileURL(Path.join(APP_DIR, "apps/server/src/orchestration-v2/testkit/fixtures/fx_early_stop/fx_transcript.ndjson")).href;
  const replaySource = FS.readFileSync(Path.join(APP_DIR, "apps/server/scripts/dev-replay-agent.ts"), "utf8")
    .replace('"./dev-replay/showcase_transcript.ndjson"', JSON.stringify(recorded));
  const project = await t3.project("demo", { "recorded-stop-agent.ts": replaySource });
  const instanceId = ProviderInstanceId.make("recorded-provider-stop");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: {}, providerInstanceMutation: { operation: "upsert", instanceId, instance: { driver: ProviderDriverKind.make("acpRegistry"), displayName: "Recorded provider stop", enabled: true, config: { source: "local", commandPath: process.execPath, commandArgs: [Path.join(project, "recorded-stop-agent.ts")] } } } });
  }).pipe(Effect.scoped));
  const { cli } = makeState(T3_HOME);
  const started = await runPromise(cli(["thread", "start", project, "Play the recorded stop", "--title", "Provider stop", "--provider", instanceId, "--model", "showcase", "--json"]));
  const providerThread = JSON.parse(started.stdout);
  const customThread = await t3.thread({ project, title: "Custom agent stop", model: "showcase", messages: ["Give me a short tour"] });
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["orchestration.dispatchCommand"]({ type: "thread.runtime-mode.set", commandId: CommandId.make(crypto.randomUUID()), threadId: ThreadId.make(customThread.threadId), runtimeMode: "approval-required" });
  }).pipe(Effect.scoped));
  await runPromise(cli(["thread", "send", customThread.threadId, "Give me a short tour again", "--wait", "--json"], [2]));
  await runPromise(withThreadTools({ baseDir: Option.some(T3_HOME), json: true }, (tools) => tools.call("t3_thread_interrupt", { threadId: customThread.threadId, reason: "Keep this exact English reason", stop: true }, OrchestratorMcpThreadInterruptResult)).pipe(Effect.provideService(GlobalFlag.LogLevel, Option.none()), Effect.provide([NetService.layer, NodeCrypto.layer])));
  await t3.open("/settings/general");
  await screen.getByLabel("Language", { exact: true }).waitFor({ timeout: 120_000 });
  await screen.getByLabel("Language", { exact: true }).tap();
  await screen.getByText("Deutsch", { exact: true }).tap();
  await screen.getByLabel("Sprache", { exact: true }).waitFor();
  await t3.open(customThread);
  await screen.getByText("Lauf unterbrochen", { exact: false }).waitFor();
  await app.screenshot("custom-agent-stop-verbatim");
  await expect(screen.getByText("Stopped by an agent: Keep this exact English reason", { exact: false })).toBeVisible();
  await t3.open({ threadId: providerThread.threadId });
  await screen.getByText("Lauf unterbrochen", { exact: false }).waitFor();
  await app.screenshot("provider-default-stop");
  await expect(screen.getByText("Vom Anbieter gestoppt", { exact: false })).toBeVisible();
});
