import { expect } from "e2e";
import { readFile, writeFile } from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { T3_HOME } from "../e2e.config.ts";
import { test, WEB } from "./t3.ts";

const forge = "http://127.0.0.1:13981";
const repository = "tester/demo";
const auth = `Basic ${Buffer.from(`tester:${process.env.PROOF_GITEA_PASSWORD}`).toString("base64")}`;
async function api(path: string, method = "GET", body?: unknown) {
  const response = await fetch(`${forge}/api/v1/${path}`, {
    method, headers: { Authorization: auth, "Content-Type": "application/json" },
    ...(body === undefined ? {} : { body: JSON.stringify(body) }),
  });
  if (!response.ok && response.status !== 404) throw new Error(`Gitea ${method} ${path}: ${response.status}`);
  return response;
}

test("Create PR follows the committed target-branch Markdown template", WEB, async ({ t3, app, screen, browser }) => {
  await api(`repos/${repository}`, "DELETE");
  await api("user/repos", "POST", { name: "demo", default_branch: "main", private: false });
  const project = await t3.project("demo", {
    "README.md": "# Greeting helpers\nA small example project.\n",
    "greet.js": 'export function greet(name) { return `Hello, ${name}!`; }\n',
    ".gitea/pull_request_template.md": "## Context\n\n## Verification\n\n## Rollback Plan\n",
  });
  const git = (...args: string[]) => execFileSync("git", args, { cwd: project, encoding: "utf8" });
  git("remote", "add", "origin", `${forge}/${repository}.git`);
  git("config", "credential.helper", '!f() { echo username=tester; echo "password=$PROOF_GITEA_PASSWORD"; }; f');
  git("push", "-u", "origin", "main");
  git("checkout", "-b", "feature/farewell");
  await writeFile(`${project}/greet.js`, 'export function greet(name) { return `Hello, ${name}!`; }\nexport function farewell(name) { return `Goodbye, ${name}!`; }\n');
  git("add", "greet.js");
  git("-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Add farewell helper");
  await writeFile(`${project}/.gitea/pull_request_template.md`, "## LOCAL UNCOMMITTED EDIT\n");
  const thread = await t3.thread({ project, title: "Add farewell helper", messages: ["Add a farewell helper."] });
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await readFile(settingsPath, "utf8"));
  const writer = JSON.parse(await readFile(process.env.PROOF_WRITER_CONFIG!, "utf8"));
  settings.textGenerators = { proofWriter: { kind: "openaiCompatible", label: "Proof writer", baseUrl: writer.baseURL, apiKey: writer.apiKey, enabled: true } };
  settings.sourceControlWriterModelSelection = { instanceId: "proofWriter", model: "gpt-6-luna" };
  await writeFile(settingsPath, JSON.stringify(settings));
  await t3.open(thread);
  await screen.getByRole("button", "Git action options").tap();
  await screen.getByRole("menuitem", "Create PR").tap();
  await screen.getByText("Created PR", { exact: true }).waitFor({ timeout: 180_000 });
  await browser.goto(`${forge}/${repository}/pulls/1`);
  await screen.getByText("feature/farewell", { exact: false }).first().waitFor();
  await app.screenshot("pr-description");
  await expect(screen.getByRole("heading", "Context", { exact: true })).toBeVisible();
  await expect(screen.getByRole("heading", "Verification", { exact: true })).toBeVisible();
  await expect(screen.getByRole("heading", "Rollback Plan", { exact: true })).toBeVisible();
  await expect(screen.getByRole("heading", "LOCAL UNCOMMITTED EDIT", { exact: true })).not.toBeVisible();
});
