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

test("A merge request created after a Bash here-string links to its thread", WEB, async ({ t3, app, screen, browser }) => {
  const call = async (args: string[]) => JSON.parse((await runPromise(run("glab", ["api", ...args]))).stdout);
  const name = `factory-49638-proof-${Date.now()}`;
  const remote = await call(["projects", "-X", "POST", "-f", `name=${name}`, "-f", "visibility=private", "-f", "initialize_with_readme=true"]);
  try {
    await call([`projects/${remote.id}/repository/branches`, "-X", "POST", "-f", "branch=feature", "-f", "ref=main"]);
    await call([`projects/${remote.id}/repository/files/update.txt`, "-X", "POST", "-f", "branch=feature", "-f", "content=Update", "-f", "commit_message=Update"]);
    const project = await t3.project("home-repo");
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client["server.updateSettings"]({
        patch: { defaultRuntimeMode: "full-access" },
        providerInstanceMutation: {
          operation: "upsert", instanceId: ProviderInstanceId.make("opencode"),
          instance: { driver: ProviderDriverKind.make("opencode"), displayName: "OpenCode", enabled: true, config: {} }
        }
      });
    }).pipe(Effect.scoped));
    const command = `base64 --decode <<<VXBkYXRlCg== > body.md
glab mr create --repo ${remote.path_with_namespace} --source-branch feature --target-branch main --title "Update" --description "$(cat body.md)" --yes`;
    const prompt = `Run exactly this as ONE multiline Bash tool invocation. Do not split or rewrite it. Do not call any T3 tools or link the merge request yourself. After it succeeds, say only Done.\n\n${command}`;
    const started = await runPromise(makeState(T3_HOME).cli(["thread", "start", project, prompt, "--title", "Create merge request after here-string", "--provider", "opencode", "--model", "anthropic/claude-haiku-4-5-20251001", "--wait", "--json"]));
    const { threadId } = JSON.parse(started.stdout);
    await browser.setViewport({ width: 1440, height: 900 });
    await t3.open({ threadId });
    await screen.getByRole("button", /^Worked for /).tap();
    await screen.getByRole("button", /^base64 --decode/).tap();
    await screen.getByText(`https://gitlab.com/${remote.path_with_namespace}/-/merge_requests/1`, { exact: false }).first().waitFor();
    await app.screenshot("created-merge-request-linked-items");
    await expect(screen.getByRole("link", "MR #1, status pending", { exact: true })).toBeVisible();
  } finally {
    await runPromise(run("glab", ["api", `projects/${remote.id}`, "-X", "DELETE"]));
  }
});
