import { expect } from "e2e";
import { ProviderInstanceId, ProviderDriverKind } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("ACP Registry models can be explicitly selected for text generation", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("text-generation-demo");
  const thread = await t3.thread({ project, title: "Text generation demo", messages: ["Show the demo"] });
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({ patch: {}, providerInstanceMutation: {
      operation: "upsert", instanceId: ProviderInstanceId.make("acpProof"), instance: {
        driver: ProviderDriverKind.make("acpRegistry"), displayName: "ACP proof replay", enabled: true,
        config: { source: "local", commandPath: process.execPath, commandArgs: [process.env.ACP_PROOF_AGENT!] },
      },
    }});
  }).pipe(Effect.scoped));
  await t3.open("/settings/threads");
  await screen.getByText("Text generation", { exact: true }).waitFor();
  await browser.evaluate(() => {
    document.getElementById("text-generation")?.scrollIntoView({ block: "center" });
    return null;
  });
  await app.screenshot("text-generation-availability");
  await expect(screen.getByText("No text generation providers available.", { exact: true })).not.toBeVisible();
  await browser.locator('#text-generation [data-chat-provider-model-picker]').tap();
  await screen.getByRole("button", "ACP proof replay", { exact: true }).tap();
  await app.screenshot("text-generation-models");
  await screen.getByRole("option", /ACP title replay/).tap();
  await t3.open("/settings/threads");
  await browser.locator('#text-generation').getByRole('button', 'ACP title replay', {exact:false}).waitFor();
  await browser.evaluate(() => { document.getElementById('text-generation')?.scrollIntoView({block:'center'}); return null; });
  await app.screenshot("saved-acp-model");
  const started = await runPromise(makeState(T3_HOME).cli(["thread", "start", project, "Summarize this project", "--generate-title", "--provider", "devReplay", "--model", "multi-turn", "--wait", "--json"]));
  const created = JSON.parse(started.stdout);
  await t3.open({ threadId: created.threadId });
  await expect(screen.getByText("ACP generated project title", { exact: true }).first()).toBeVisible();
  await app.screenshot("acp-generated-title");
});
