import { createServer } from "node:http";
import { readFile, mkdir } from "node:fs/promises";
import { join } from "node:path";
import * as NodeWS from "@effect/platform-node/NodeWS";
import {
  ORCHESTRATION_PROTOCOL_VERSION,
  WsRpcGroup,
} from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
import { RpcClient, RpcSerialization } from "effect/rpc";
import { Socket } from "effect/socket";

import { T3_HOME } from "../e2e.config.ts";
import { SECOND_HOME, startSecondServer } from "./draft-default-server.ts";
import { run } from "./shell.ts";
import { makeState, runPromise, test, WEB } from "./t3.ts";

/** The typed RPC client of the server on `home` at `origin`, signed in through its own CLI. */
const rpcClient = Effect.fn("scenario.rpcClient")(function* (home: string, origin: string) {
  const issued = yield* makeState(home).cli(["auth", "session", "issue", "--token-only"]);
  const { ticket } = yield* HttpClient.execute(
    HttpClientRequest.post(`${origin}/api/auth/websocket-ticket`).pipe(
      HttpClientRequest.bearerToken(issued.stdout.trim()),
    ),
  ).pipe(
    Effect.flatMap(HttpClientResponse.filterStatusOk),
    Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))),
    Effect.provide(FetchHttpClient.layer),
  );
  // Built into the caller's scope: `Effect.provide` would close the socket once `make` returns.
  const protocol = yield* Layer.build(
    RpcClient.layerProtocolSocket().pipe(
      Layer.provide(
        Socket.layerWebSocket(
          `${origin.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket)}`,
        ),
      ),
      Layer.provide(RpcSerialization.layerJson),
      Layer.provide(NodeWS.layerWebSocketConstructor),
    ),
  );
  return yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
});


const setDefault = (home: string, origin: string, model: string) => runPromise(Effect.gen(function* () {
  const client = yield* rpcClient(home, origin);
  yield* client["server.updateSettings"]({ patch: { defaultModelSelection: { instanceId: "devReplay", model } } });
}).pipe(Effect.scoped));

test("Unsent drafts adopt destination defaults through Run on, Add project, and the project picker", WEB,
async ({ t3, app, screen, browser }) => {
  const publicRoot = join(T3_HOME, "public");
  await mkdir(join(publicRoot, "scenario"), {recursive:true});
  const http = createServer(async (req,res) => {
    try { const data = await readFile(join(publicRoot, new URL(req.url!, "http://localhost").pathname)); res.end(data); }
    catch {res.statusCode=404;res.end();}
  });
  await new Promise<void>(resolve => http.listen(0,"127.0.0.1",resolve));
  const port = (http.address() as {port:number}).port;
  // Configure remotes before adding projects, so the first identity lookup sees them.
  const config = (remote:string) => `[remote "origin"]\nurl = ${remote}\nfetch = +refs/heads/*:refs/remotes/origin/*\n`;
  const workspace = await t3.project("demo", {".git/config": config("https://github.com/scenario/demo.git")});
  const cloneWorkspace = await t3.project("clone-demo", {".git/config": config(`http://127.0.0.1:${port}/scenario/clone-demo.git`)});
  await runPromise(run("git", ["clone", "--bare", cloneWorkspace, join(publicRoot, "scenario/clone-demo.git")]));
  await runPromise(run("git", ["update-server-info"], {cwd:join(publicRoot, "scenario/clone-demo.git")}));
  const demoThread = await t3.thread({project:workspace, title:"Earlier demo work", messages:["first"]});
  const cloneThread = await t3.thread({project:cloneWorkspace, title:"Earlier clone work", messages:["first"]});
  const server = startSecondServer(app.baseUrl ?? "");
  try {
    const {host, token} = await server.ready;
    await runPromise(makeState(SECOND_HOME).cli(["project", "add", workspace, "--title", "demo"]));
    await makeState(SECOND_HOME).state.project("destination-project");
    await setDefault(T3_HOME, app.baseUrl ?? "", "todo-list");
    await setDefault(SECOND_HOME, host, "showcase");
    await t3.open("/settings/connections");
    await screen.getByRole("button", "Add environment").tap();
    const dialog = screen.getByRole("dialog");
    await dialog.getByPlaceholder("backend.example.com").fill(host);
    await dialog.getByPlaceholder("PAIRCODE").fill(token);
    await dialog.getByRole("button", "Add environment").tap();
    await screen.getByRole("button", "More actions for Destination").waitFor({state: "visible", timeout:60000});
    await t3.open(demoThread);
    await screen.getByRole("button", "New thread in demo", {exact:true}).tap();
    await screen.getByRole("textbox").fill("Hello from an untouched draft");
    await app.screenshot("initial-draft-default");
    const startedOnSource = await screen.getByRole("button", "Plan and reads", {exact:false}).first().isVisible();
    const destination = startedOnSource ? "Destination" : "Scenario";
    const expectedModel = startedOnSource ? "Showcase" : "Plan and reads";
    const runOn = () => screen.getByText(/^(Scenario|Destination)$/).last().tap();
    await runOn();
    await screen.getByRole("menuitemradio", destination, {exact:true}).tap();
    await runOn();
    await app.screenshot("run-on-destination-default");
    await browser.keyboard.press("Escape");
    await expect.soft(screen.getByRole("button", expectedModel, {exact:false}).first()).toBeVisible();

    // The project picker retargets the same typed draft using the shared helper.
    await browser.locator('[data-draft-project-trigger]').click();
    await screen.getByRole("option", "destination-project", {exact:false}).tap();
    await app.screenshot("project-picker-default");
    await expect.soft(screen.getByRole("button", "Showcase", {exact:false}).first()).toBeVisible();

    // An explicit choice must survive a machine change.
    await screen.getByRole("button", "Showcase", {exact:false}).first().tap();
    await browser.keyboard.type("Write approval");
    await browser.keyboard.press("Enter");
    await t3.open(demoThread);
    await screen.getByRole("button", "New thread in demo", {exact:true}).tap();
    await screen.getByRole("textbox").fill("Explicit selection stays selected");
    await screen.getByRole("button", /Showcase|Plan and reads/, {exact:false}).first().tap();
    await browser.keyboard.type("Write approval");
    await browser.keyboard.press("Enter");
    await runOn();
    const currentSource = await screen.getByRole("menuitemradio", "Scenario", {exact:true}).getAttribute("aria-checked");
    await screen.getByRole("menuitemradio", currentSource === "true" ? "Destination" : "Scenario", {exact:true}).tap();
    await app.screenshot("explicit-choice-preserved");
    await expect.soft(screen.getByRole("button", "Write approval", {exact:false}).first()).toBeVisible();

    // Add project to another machine must move the existing unsent draft as well.
    await t3.open(cloneThread);
    await screen.getByRole("button", "New thread in clone-demo", {exact:true}).tap();
    await screen.getByRole("textbox").fill("Hello through Add project to another machine");
    await app.screenshot("add-project-source-default");
    await runOn();
    await screen.getByRole("menuitem", "Add to another machine", {exact:true}).tap();
    await screen.getByRole("menuitem", "Destination", {exact:true}).tap();
    const cloneDialog = screen.getByRole("dialog");
    await cloneDialog.getByRole("textbox").first().fill(join(SECOND_HOME, "cloned-demo"));
    await app.screenshot("add-project-dialog");
    await cloneDialog.getByRole("button", "Clone to Destination", {exact:true}).tap();
    await screen.getByRole("dialog").waitFor({state:"hidden"});
    await screen.getByText("Cloning", {exact:false}).waitFor({state:"hidden"});
    await app.screenshot("add-project-destination-default");
    await expect.soft(screen.getByRole("button", "Showcase", {exact:false}).first()).toBeVisible();
  } finally { await server.stop(); await new Promise<void>(resolve=>http.close(()=>resolve())); }
});
