import { writeFileSync } from "node:fs";
import { execFileSync } from "node:child_process";

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

const glab = (args: string[]) => JSON.parse(execFileSync("glab", ["api", ...args], { encoding: "utf8" }));
const git = (cwd: string, args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });

test("Review watch preserves HTML after an over-indented fence", WEB, async ({ t3, app, screen, browser }) => {
  const projectId = process.env.FENCE_PROJECT_ID!;
  const remote = process.env.FENCE_REMOTE!;
  const project = await t3.project("fence-demo");
  const branch = `proof-${Date.now()}`;
  git(project, ["remote", "add", "origin", remote]);
  git(project, ["fetch", "origin", "main"]);
  git(project, ["checkout", "-B", branch, "FETCH_HEAD"]);
  git(project, ["-c", "user.name=Scenario", "-c", "user.email=scenario@example.invalid", "commit", "--allow-empty", "-m", "Review fence example"]);
  git(project, ["push", "-u", "origin", branch]);
  const mr = glab(["-X", "POST", `projects/${projectId}/merge_requests`, "-f", `source_branch=${branch}`, "-f", "target_branch=main", "-f", "title=Review fence example"]);
  try {
    const thread = await t3.thread({ project, title: "Review fence example", messages: ['Review this example. See :codex-file-citation{path="server-wake.txt" line_range_start="1"}'], model: "multi-turn" });
    await runPromise(Effect.gen(function* () {
      const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
      yield* client["orchestration.dispatchCommand"]({
        type: "thread.pull-request.link", commandId: CommandId.make(crypto.randomUUID()),
        threadId: ThreadId.make(thread.threadId), host: "gitlab.com",
        repository: new URL(remote).pathname.slice(1).replace(/\.git$/, ""),
        number: mr.iid, url: mr.web_url, source: "manual",
      });
    }).pipe(Effect.scoped));
    await browser.setViewport({ width: 1920, height: 1080 });
    await t3.open(thread);
    await screen.getByRole("button", "Toggle right panel").tap();
    await screen.getByRole("button", "Add panel surface").tap();
    await screen.getByRole("menuitem", "Linked items", { exact: false }).tap();
    await browser.locator(`a[href="${mr.web_url}"]`).last().hover();
    await screen.getByRole("button", `Actions for #${mr.iid}`).tap();
    await screen.getByRole("menuitem", "Watch for changes").tap();
    await app.screenshot("watching");
    const body = "```html\n    ```\n<div>KEEP</div>\n```";
    const response = await fetch(`https://gitlab.com/api/v4/projects/${projectId}/merge_requests/${mr.iid}/notes`, {
      method: "POST", headers: { "PRIVATE-TOKEN": process.env.FENCE_BOT_TOKEN!, "Content-Type": "application/json" }, body: JSON.stringify({ body }),
    });
    if (!response.ok) throw new Error(`Posting real GitLab comment failed: ${response.status}`);
    await screen.getByText(`#${mr.iid}: new comments`, { exact: false }).first().waitFor({ state: "visible", timeout: 180_000 });
    const rows = JSON.parse(execFileSync("sqlite3", ["-readonly", "-json", `${T3_HOME}/userdata/statev2.sqlite`,
      `SELECT payload_json FROM orchestration_v2_projection_messages WHERE thread_id='${thread.threadId}' AND json_extract(payload_json, '$.notification.summary') LIKE '%new comments%' ORDER BY created_at DESC LIMIT 1`], { encoding: "utf8" }));
    const wake = rows[0] ? JSON.parse(rows[0].payload_json) : undefined;
    if (!wake) throw new Error("No persisted review wake message");
    writeFileSync(`${project}/server-wake.txt`, wake.text);
    writeFileSync(`${process.env.FENCE_OUTPUT}/server-wake.txt`, wake.text);
    await screen.getByRole("button", /^Agent Review this example/).tap();
    await screen.getByRole("link", /^server-wake.txt/).tap();
    await screen.getByRole("button", "Maximize panel").tap();
    await screen.getByRole("button", "Toggle main sidebar").tap();
    await expect.poll(() => browser.evaluate(() => {
      for (const host of document.querySelectorAll("*")) {
        const content = host.shadowRoot?.querySelector("[data-content]");
        if (content) return content.textContent ?? "";
      }
      return "";
    }), { timeout: 30_000 }).toContain("Update on pull request");
    await app.screenshot("review-wake");
    await new Promise((resolve) => setTimeout(resolve, 500));
    await app.screenshot("review-wake-stable");

  } finally {
    glab(["-X", "PUT", `projects/${projectId}/merge_requests/${mr.iid}`, "-f", "state_event=close"]);
    git(project, ["push", "origin", "--delete", branch]);
  }
});
