import { expect } from "e2e";
import { CommandId, ThreadId } from "@t3tools/contracts";
import { randomUUID } from "node:crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { FetchHttpClient, HttpClient, HttpClientRequest } from "effect/http";

import { T3_HOME } from "../e2e.config.ts";
import { ScenarioError } from "./shell.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

const SettingsJson = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown));
const decodeSettings = Schema.decodeEffect(SettingsJson);
const encodeSettings = Schema.encodeEffect(SettingsJson);

// A token from `auth session issue` acts at most in approval-required mode, so the thread must too.
const approvalRequiredThreads = Effect.gen(function* () {
  const fs = yield* FileSystem.FileSystem;
  const settingsPath = (yield* Path.Path).join(T3_HOME, "userdata/settings.json");
  const original = yield* fs.readFileString(settingsPath);
  const settings = yield* decodeSettings(original);
  return {
    apply: fs.writeFileString(
      settingsPath,
      yield* encodeSettings({
        ...settings,
        defaultRuntimeMode: "approval-required",
        sidebarAutoSettleOnMerge: true,
      }),
    ),
    restore: fs.writeFileString(settingsPath, original),
  };
});

/** Archives a thread as an outside agent does: `t3_thread_organize` on the server's MCP endpoint. */
const callMcp = Effect.fn("scenario.archiveOverMcp")(function* (
  baseUrl: string,
  threadId: string, name: string, args: Record<string, unknown>,
) {
  const { cli } = makeState(T3_HOME);
  const { stdout } = yield* cli([
    "auth",
    "session",
    "issue",
    "--subject",
    "mcp-client",
    "--scope",
    "orchestration:read",
    "--scope",
    "orchestration:operate",
    "--token-only",
  ]);
  const client = yield* HttpClient.HttpClient;
  let sessionId: string | null = null;
  const send = Effect.fnUntraced(function* (message: object) {
    const response = yield* client.execute(
      HttpClientRequest.post(`${baseUrl}/mcp`).pipe(
        HttpClientRequest.setHeaders({
          accept: "application/json, text/event-stream",
          authorization: `Bearer ${stdout.trim()}`,
          ...(sessionId === null ? {} : { "mcp-session-id": sessionId }),
        }),
        HttpClientRequest.bodyJsonUnsafe({ jsonrpc: "2.0", ...message }),
      ),
    );
    sessionId = response.headers["mcp-session-id"] ?? sessionId;
    const body = yield* response.text;
    if (response.status >= 300) {
      return yield* new ScenarioError({ message: `MCP ${response.status}: ${body}` });
    }
    return body;
  });
  yield* send({
    id: 1,
    method: "initialize",
    params: {
      protocolVersion: "2025-06-18",
      capabilities: {},
      clientInfo: { name: "scenario", version: "1" },
    },
  });
  yield* send({ method: "notifications/initialized" });
  const result = yield* send({
    id: 2,
    method: "tools/call",
    params: { name, arguments: { threadId, ...args } },
  });
  const data = result.split("\n").find((line) => line.startsWith("data:"));
  return JSON.parse(data ? data.slice(5) : result);
}, Effect.provide(FetchHttpClient.layer));

const dispatch = (origin: string, command: object) => runPromise(Effect.gen(function* () {
  const client = yield* rpcClient(T3_HOME, origin);
  return yield* client["orchestration.dispatchCommand"]({ ...command, commandId: CommandId.make(randomUUID()) } as never);
}).pipe(Effect.scoped));
const projection = (origin: string, threadId: string) => runPromise(Effect.gen(function* () {
  const client = yield* rpcClient(T3_HOME, origin);
  return yield* client["orchestration.getThreadProjection"]({ threadId: ThreadId.make(threadId) });
}).pipe(Effect.scoped));

test("An outside agent disables auto-settle for merged-PR follow-up work and restores it", WEB, async ({ t3, app, screen, browser }) => {
  const settings = await runPromise(approvalRequiredThreads);
  await runPromise(settings.apply);
  const project = await t3.project("follow-up-demo");
  const thread = await t3.thread({ project, title: "Merged PR follow-up", messages: ["Initial work"], model: "multi-turn" });
  const origin = app.baseUrl ?? "";
  const call = (name: string, args: Record<string, unknown>) => runPromise(callMcp(origin, thread.threadId, name, args));
  const key = { host: "example.invalid", repository: "demo/follow-up", number: 1 };
  await dispatch(origin, { type: "thread.pull-request.link", threadId: thread.threadId, ...key, url: "https://example.invalid/demo/follow-up/pull/1", source: "agent" });
  const now = new Date().toISOString();
  await dispatch(origin, { type: "thread.pull-request-link.sync", threadId: thread.threadId, ...key, stack: null, snapshot: { state: "merged", title: "Synthetic merged PR", headBranch: "feature", baseBranch: "main", isDraft: false, updatedAt: now, syncedAt: now, mergedAt: now } });
  await t3.open(thread);
  await expect.poll(async () => (await projection(origin, thread.threadId)).thread.settledOverride, { timeout: 60000 }).toBe("settled");
  await call("t3_thread_send", { message: "First follow-up", mode: "auto" });
  await call("t3_thread_wait", { timeoutMs: 60000 });
  await expect.poll(async () => (await projection(origin, thread.threadId)).thread.settledOverride, { timeout: 60000 }).toBe("settled");
  const disabled = await call("t3_thread_organize", { action: "disable_auto_settle" });
  console.log("disable_auto_settle response", JSON.stringify(disabled));
  await screen.getByRole("button", "Thread actions for Merged PR follow-up").tap();
  await screen.getByRole("menuitem", "Auto-settle behavior").hover();
  await app.screenshot("agent-disable-auto-settle");
  expect(disabled.result?.isError ?? Boolean(disabled.error)).toBe(false);
  await expect(screen.getByRole("menuitemradio", "Never")).toBeChecked();
  await browser.keyboard.press("Escape");
  await browser.keyboard.press("Escape");
  for (const message of ["Second follow-up", "Third follow-up"]) {
    const sent = await call("t3_thread_send", { message, mode: "auto" });
    expect(sent.result?.isError ?? Boolean(sent.error)).toBe(false);
    await call("t3_thread_wait", { timeoutMs: 60000 });
    const state = await projection(origin, thread.threadId);
    console.log("follow-up completion", JSON.stringify({ message, disabled: state.thread.autoSettleDisabledAt != null, settled: state.thread.settledOverride }));
    expect(state.thread.autoSettleDisabledAt).not.toBeNull();
    expect(state.thread.settledOverride).toBeNull();
  }
  await screen.getByRole("button", "Thread actions for Merged PR follow-up").tap();
  await screen.getByRole("menuitem", "Auto-settle behavior").hover();
  await app.screenshot("follow-ups-stay-active");
  await expect(screen.getByRole("menuitemradio", "Never")).toBeChecked();
  await browser.keyboard.press("Escape");
  await browser.keyboard.press("Escape");
  const enabled = await call("t3_thread_organize", { action: "enable_auto_settle" });
  console.log("enable_auto_settle response", JSON.stringify(enabled));
  await expect.poll(async () => (await projection(origin, thread.threadId)).thread.settledOverride, { timeout: 60000 }).toBe("settled");
  expect(enabled.result?.isError ?? Boolean(enabled.error)).toBe(false);
  await screen.getByRole("button", "Thread actions for Merged PR follow-up").tap();
  await screen.getByRole("menuitem", "Auto-settle behavior").hover();
  await expect(screen.getByRole("menuitemradio", "Follow settings")).toBeChecked();
  await app.screenshot("agent-restores-follow-settings");
});
