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

const deliver = Effect.fn("scenario.deliver")(function* (origin: string, form: boolean) {
  const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]);
  const { projects } = yield* HttpClient.execute(HttpClientRequest.get(`${origin}/api/projects`).pipe(HttpClientRequest.bearerToken(issued.stdout.trim()))).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.flatMap(HttpClientResponse.schemaBodyJson(ProjectSnapshot)));
  const client = yield* rpcClient(T3_HOME, origin);
  const { task } = yield* client["scheduledTasks.upsert"]({
    title: form ? "Kind hook form" : "Kind hook query",
    prompt: form ? "Kind: {{body.?kind}} | body.kind={{body.kind}} | query.?kind={{query.?kind}} | query.kind={{query.kind}} | query={{query}}" : "Kind: {{query.?kind}}",
    enabled: true, schedule: { type: "webhook" },
    projectId: projects.find(p => p.title === "Webhook proof")!.id,
    workspaceStrategy: { type: "root" },
    modelSelection: { instanceId: ProviderInstanceId.make("devReplay"), model: "showcase" }, runtimeMode: "full-access", interactionMode: "default",
  });
  const request = HttpClientRequest.post(`${origin}${task.webhook!.path}??kind=opened`);
  yield* HttpClient.execute(form ? request.pipe(HttpClientRequest.bodyText("?kind=opened", "application/x-www-form-urlencoded")) : request.pipe(HttpClientRequest.bodyJsonUnsafe({}))).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk));
}, Effect.scoped, Effect.provide(FetchHttpClient.layer));

test("Literal question marks remain part of query and form parameter names", WEB, async ({t3, app, screen, browser}) => {
  await t3.project("Webhook proof");
  const prompts: string[] = [];
  for (const form of [false, true]) {
    await runPromise(deliver(app.baseUrl ?? "", form));
    await t3.open("/settings/scheduled-tasks");
    await screen.getByRole("button", `Actions for Kind hook ${form ? "form" : "query"}`).tap();
    await screen.getByRole("menuitem", "Deliveries").tap();
    const dialog = screen.getByRole("dialog");
    await dialog.getByRole("button", /POST/).tap();
    await dialog.getByText("Prompt sent to the agent", {exact: true}).waitFor();
    prompts.push((await browser.evaluate(() => document.querySelector("[role=dialog] pre")?.textContent ?? "")).split("\n\nText between ")[0]);
    await app.screenshot(form ? "form-and-query-delivery" : "query-delivery");
  }
  expect(prompts[0]).toMatch(/^Kind: <webhook-data[^>]*>opened<\/webhook-data[^>]*>$/);
  expect(prompts[1]).toMatch(/^Kind: <webhook-data[^>]*>opened<\/webhook-data[^>]*> \| body.kind= \| query\.\?kind=<webhook-data[^>]*>opened<\/webhook-data[^>]*> \| query.kind= \| query=<webhook-data[^>]*>\{\s*"\?kind":\s*"opened"\s*\}<\/webhook-data[^>]*>$/);
});
