import { expect } from "e2e";
import { execFileSync } from "node:child_process";
import * as fs from "node:fs";
import { test, WEB, makeState, runPromise } from "./t3.ts";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";

const pause = (ms: number) => new Promise(r => setTimeout(r, ms));
function command(cmd: string, args: string[], cwd?: string) {
  return execFileSync(cmd, args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
}
function api(path: string, args: string[] = []) { return JSON.parse(command("glab", ["api", path, ...args])); }

test("GitLab draft MR is draft in its initial open webhook and settled thread row", WEB, async ({ t3, app, browser, screen }) => {
  const tag = `draft-proof-${Date.now()}`;
  const project = api("projects", ["-X", "POST", "-f", `name=${tag}`, "-f", "visibility=private"]);
  const hook = await (await fetch("https://webhook.site/token", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ default_status: 200 }) })).json();
  try {
    api(`projects/${project.id}/hooks`, ["-X", "POST", "-f", `url=https://webhook.site/${hook.uuid}`, "-f", "merge_requests_events=true"]);
    const workspace = await t3.project("Remote flow", { "flow.txt": "initial\n" });
    command("git", ["remote", "add", "origin", project.http_url_to_repo], workspace);
    command("git", ["push", "-u", "origin", "main"], workspace);
    command("git", ["switch", "-c", "feature/fix-remote-flow"], workspace);
    fs.writeFileSync(`${workspace}/flow.txt`, "initial\nFix remote flow\n");
    command("git", ["add", "flow.txt"], workspace);
    command("git", ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "-m", "Fix remote flow"], workspace);
    command("git", ["push", "-u", "origin", "feature/fix-remote-flow"], workspace);
    const thread = await t3.thread({ project: workspace, title: "Create draft merge request", messages: ["Create a draft MR titled Fix remote flow with body Repro."] });
    await t3.open(thread);
    let env: Record<string,string> | undefined;
    for (const pid of fs.readdirSync("/proc").filter(x => /^\d+$/.test(x))) {
      try {
        const candidate = Object.fromEntries(fs.readFileSync(`/proc/${pid}/environ`, "utf8").split("\0").map(x => { const i=x.indexOf("="); return [x.slice(0,i),x.slice(i+1)]; }));
        if (candidate.T3CODE_THREAD_ID === thread.threadId && candidate.T3_ACP_MCP_AUTHORIZATION) { env = candidate; break; }
      } catch {}
    }
    if (!env) throw new Error("Replay thread MCP session not found");
    const headers: Record<string,string> = { authorization: env.T3_ACP_MCP_AUTHORIZATION, accept: "application/json, text/event-stream", "content-type": "application/json" };
    const send = (id: number, method: string, params: unknown) => fetch(env!.T3_ACP_MCP_ENDPOINT, { method: "POST", headers, body: JSON.stringify({ jsonrpc: "2.0", id, method, params }) });
    const init = await send(1, "initialize", { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "draft-proof", version: "1" } });
    headers["mcp-session-id"] = init.headers.get("mcp-session-id")!;
    headers["mcp-protocol-version"] = "2025-06-18";
    await runPromise(makeState(T3_HOME).cli(["thread", "send", thread.threadId, "Call pull_request_create now with draft true.", "--json"]));
    const result = await (await send(2, "tools/call", { name: "pull_request_create", arguments: { title: "Fix remote flow", body: "Repro", draft: true } })).text();
    if (result.includes('"isError":true')) throw new Error(result);
    let events: any[] = [];
    for (let i=0;i<30;i++) {
      const received = await (await fetch(`https://webhook.site/token/${hook.uuid}/requests?sorting=oldest`)).json();
      events = received.data.map((r: any) => { try { return JSON.parse(r.content); } catch { return {}; } });
      if (events.some(e => e.object_attributes?.action === "open")) break;
      await pause(1000);
    }
    const opened = events.find(e => e.object_attributes?.action === "open");
    if (!opened) throw new Error("GitLab open webhook was not delivered");
    await pause(40000);
    const summary = { action: opened.object_attributes.action, title: opened.object_attributes.title, draft: opened.object_attributes.draft, work_in_progress: opened.object_attributes.work_in_progress };
    console.log("INITIAL_GITLAB_WEBHOOK", JSON.stringify(summary));
    const mr = api(`projects/${project.id}/merge_requests/1`);
    console.log("FINAL_GITLAB_MR", JSON.stringify({ title: mr.title, draft: mr.draft }));
    const sha = command("git", ["rev-parse", "HEAD"], APP_DIR);
    fs.writeFileSync(`/tmp/factory-pr-39817-evidence-2/${sha}-webhook.json`, JSON.stringify({
      commit: sha, source: "GitLab merge_request webhook delivered to temporary external receiver",
      initialEvent: { object_kind: opened.object_kind, event_type: opened.event_type, object_attributes: {
        action: opened.object_attributes.action, title: opened.object_attributes.title,
        draft: opened.object_attributes.draft, work_in_progress: opened.object_attributes.work_in_progress,
        state: opened.object_attributes.state, created_at: opened.object_attributes.created_at,
        updated_at: opened.object_attributes.updated_at,
        source_branch: opened.object_attributes.source_branch, target_branch: opened.object_attributes.target_branch
      } }, finalMr: { title: mr.title, draft: mr.draft }
    }, null, 2));
    let previous = await app.screenshot("settled-draft-row");
    let stable = false;
    for (let i = 0; i < 10; i++) {
      await pause(500);
      const current = await app.screenshot(`settled-confirmation-${i + 1}`);
      try { command("compare", ["-metric", "AE", previous, current, "null:"]); stable = true; break; } catch {}
      previous = current;
    }
    if (!stable) throw new Error("Viewport did not settle to identical screenshots");
    await expect(screen.getByText("Ready", { exact: true }).first()).toBeVisible();
    expect(summary.draft ?? summary.work_in_progress, "Initial GitLab open webhook is draft").toBe(true);
    await expect(screen.getByText("Draft: Fix remote flow", { exact: false }).first()).toBeVisible();
  } finally {
    api(`projects/${project.id}`, ["-X", "DELETE"]);
    await fetch(`https://webhook.site/token/${hook.uuid}`, { method: "DELETE" });
  }
});
