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

test("Azure default ref preserves its trailing nonbreaking space when loading PR templates", WEB, async ({ t3, app, screen }) => {
  const org = process.env.AZURE_DEVOPS_TEST_ORG!;
  const projectName = process.env.AZURE_DEVOPS_TEST_PROJECT!;
  const az = async (...args: string[]) => JSON.parse((await runPromise(run("az", [...args, "--organization", org, "--project", projectName, "-o", "json"]))).stdout);
  const repo = await az("repos", "create", "--name", `pr48414-proof-${Date.now()}`);
  const api = async (path: string, method: string, body: unknown) => {
    const response = await fetch(`${org}/${encodeURIComponent(projectName)}/_apis/git/repositories/${repo.id}${path}?api-version=7.1`, { method, headers: { Authorization: `Basic ${Buffer.from(`:${process.env.AZURE_DEVOPS_EXT_PAT}`).toString("base64")}`, "Content-Type": "application/json" }, body: JSON.stringify(body) });
    if (!response.ok) throw new Error(`Azure REST ${response.status}`);
    return response.json();
  };
  try {
    const project = await t3.project("Zebra template proof", { "pull_request_template.md": "## Zebra Checklist\n- [ ] Zebra stripes verified\n\n## Rollback Plan\nDescribe how to revert this change.\n" });
    const git = (...args: string[]) => runPromise(run("git", args, { cwd: project }));
    await git("remote", "add", "origin", repo.remoteUrl);
    await git("config", "credential.helper", '!f() { echo username=pat; echo "password=$AZURE_DEVOPS_EXT_PAT"; }; f');
    await git("push", "-u", "origin", "main");
    const sha = (await git("rev-parse", "HEAD")).stdout.trim();
    await api("/refs", "POST", [{ name: "refs/heads/release\u00a0", oldObjectId: "0".repeat(40), newObjectId: sha }]);
    await api("", "PATCH", { defaultBranch: "refs/heads/release\u00a0" });
    await git("fetch", "origin");
    await git("remote", "set-head", "origin", "-a");
    await git("switch", "-c", "feature/greeting");
    await writeFile(`${project}/greet.ts`, 'export const greet = (name: string): string => `Hello, ${name}!`;\n');
    await git("add", "greet.ts");
    await git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Add typed greeting helper");
    const thread = await t3.thread({ project, title: "Create greeting PR", messages: ["Start"], model: "multi-turn" });
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl!);
      yield* client["server.updateSettings"]({ patch: { sourceControlWriterModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-6-luna" }, sourceControlWritingStyle: { followChangeRequestTemplates: true } }, providerInstanceMutation: { operation: "upsert", instanceId: ProviderInstanceId.make("codex"), instance: { driver: "codex", enabled: true, config: { binaryPath: "/usr/local/bin/codex" } } } });
    }).pipe(Effect.scoped));
    await t3.open(thread);
    await screen.getByRole("button", "Push & create PR", { exact: true }).tap({ timeout: 120_000 });
    await screen.getByText(/Created PR|Action failed/).waitFor({ timeout: 180_000 });
    const prs = await az("repos", "pr", "list", "--repository", repo.id, "--source-branch", "feature/greeting");
    const pr = prs[0];
    if (!pr) { await app.screenshot("template-description"); throw new Error("App did not create Azure PR"); }
    await t3.open(`/pull-requests?${new URLSearchParams({ repository: `${projectName}/${repo.name}`, number: String(pr.pullRequestId), selectedHost: new URL(org).hostname })}`);
    await screen.getByRole("button", new RegExp(`Open #${pr.pullRequestId} `)).tap({ timeout: 60_000 });
    await screen.getByRole("heading", pr.description.split("\n").find((line: string) => line.startsWith("## ")).slice(3), { exact: true }).waitFor({ timeout: 90_000 });
    await app.screenshot("template-description");
    expect(pr.description).toContain("## Zebra Checklist");
    expect(pr.description).toContain("## Rollback Plan");
  } finally {
    await runPromise(run("az", ["repos", "delete", "--id", repo.id, "--yes", "--organization", org, "--project", projectName]));
  }
});
