import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { ProviderInstanceId } from "@t3tools/contracts";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB, rpcClient, runPromise } from "./t3.ts";

test("A failed first Claude workspace probe retains machine commands", WEB, async ({t3, app, screen, browser}) => {
  const control = await t3.project("control");
  await runPromise(Effect.gen(function*(){
    const rpc = yield* rpcClient(T3_HOME, app.baseUrl!);
    yield* rpc.subscribeServerConfig({}).pipe(Stream.filter(event => {
      const providers = event.type === "snapshot" ? event.config.providers : event.type === "providerStatuses" ? event.payload.providers : [];
      return providers.some(p => p.instanceId === "devReplay" && p.models?.some(m => m.slug === "multi-turn"));
    }), Stream.runHead);
  }).pipe(Effect.scoped, Effect.timeout("60 seconds")));
  const thread = await t3.thread({project: control, title: "Workspace command discovery", messages: ["Hello"]});
  const wrapper = path.join(T3_HOME, "claude-probe-wrapper.sh");
  await fs.writeFile(wrapper, '#!/bin/sh\ncase "$PWD" in */fresh-ws) exec sleep 120 ;; esac\nexec /usr/local/bin/claude "$@"\n', {mode: 0o755});
  const settingsPath = path.join(T3_HOME, "userdata/settings.json");
  const original = await fs.readFile(settingsPath, "utf8");
  const settings = JSON.parse(original);
  settings.providerInstances.claudeAgent = {driver: "claudeAgent", enabled: true, config: {binaryPath: wrapper}};
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  try {
    await t3.open(thread);
    const refresh = (input: object) => runPromise(Effect.gen(function*(){
      const rpc = yield* rpcClient(T3_HOME, app.baseUrl!);
      return yield* rpc["server.refreshProviders"]({instanceId: ProviderInstanceId.make("claudeAgent"), ...input});
    }).pipe(Effect.scoped));
    const machine = await refresh({fresh: true});
    if (!JSON.stringify(machine).includes('code-review')) throw new Error("Real Claude machine probe did not return code-review: " + JSON.stringify(machine));
    const project = await t3.project("fresh-ws");
    const fresh = await t3.thread({project, title: "Fresh workspace", messages: ["Hello"]});
    await t3.open(fresh);
    await browser.locator("[data-chat-provider-model-picker]").tap();
    await screen.getByPlaceholder("Search models...").fill("Sonnet");
    await screen.getByRole("option", /Sonnet/).first().tap();
    await browser.keyboard.press("Escape");
    await refresh({cwd: project});
    const composer = screen.getByTestId("composer-editor");
    await composer.fill("/code-review");
    await browser.mouse.move(280, 300);
    try {
      await expect(screen.getByRole("option", /^\/code-review\s/)).toBeVisible({timeout: 15000});
    } finally {
      await app.screenshot("failed-workspace-probe-command-list");
    }
  } finally {
    await fs.writeFile(settingsPath, original);
  }
});
