import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { CommandId, MessageId, ThreadId } from "@t3tools/contracts";
import { randomUUID } from "node:crypto";
import { MOBILE_T3_HOME } from "../e2e.config.ts";
import { IOS, test } from "./t3-mobile.ts";
import { makeState, rpcClient, runPromise } from "./t3.ts";

test("Mobile goal actions preserve an unsent draft", IOS, async ({ t3, app, screen }) => {
  const project = await t3.project("Goal demo");
  const settingsPath = path.join(MOBILE_T3_HOME, "userdata/settings.json");
  const settings = JSON.parse(await fs.readFile(settingsPath, "utf8"));
  settings.providerInstances.codex = { driver: "codex", enabled: true, config: { binaryPath: "/usr/local/bin/codex" } };
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  const { cli } = makeState(MOBILE_T3_HOME);
  const pause = (threadId: string, send = true) => runPromise(Effect.gen(function* () {
    const raw = yield* Effect.promise(() => fs.readFile(path.join(MOBILE_T3_HOME, "userdata/server-runtime.json"), "utf8"));
    const { origin } = JSON.parse(raw);
    const client = yield* rpcClient(MOBILE_T3_HOME, origin);
    yield* client["orchestration.subscribeThread"]({ threadId: ThreadId.make(threadId) }).pipe(
      Stream.filter((item) => item.kind === "snapshot"
        ? item.projection.providerThreads.some((thread) => thread.goal?.status === "active")
        : item.kind === "event" && item.event.type === "provider-thread.updated" && item.event.payload.goal?.status === "active"),
      Stream.take(1), Stream.runDrain,
    );
    if (send) yield* client["orchestration.dispatchCommand"]({
      type: "message.dispatch", commandId: CommandId.make(randomUUID()),
      threadId: ThreadId.make(threadId), messageId: MessageId.make(randomUUID()),
      createdBy: "user", creationSource: "mobile", text: "/goal pause", attachments: [],
      deliveryIntent: "steer", dispatchMode: { type: "queue_after_active" },
    });
  }).pipe(Effect.scoped));
  const started = await runPromise(cli(["thread", "start", project,
    "/goal Create a file named hello.txt containing the word hello, then stop",
    "--title", "Goal actions", "--provider", "codex", "--model", "gpt-6-luna", "--wait", "--json"]));
  const { threadId } = JSON.parse(started.stdout);
  await t3.open();
  await screen.getByText("Goal actions", { exact: false }).first().tap();
  await screen.getByText("Goal complete", { exact: false }).first().waitFor({ timeout: 120_000 });
  await app.screenshot("completed-goal");
  await runPromise(cli(["thread", "send", threadId,
    "/goal Print the numbers 1 to 40 one at a time, running sleep 3 in the shell between each number", "--json"]));
  await screen.getByRole("button", "Stop agent").first().waitFor({ timeout: 120_000 });
  await pause(threadId);
  await screen.getByText("Goal paused", { exact: false }).first().waitFor({ timeout: 120_000 });
  const composer = screen.getByRole("textbox").first();
  await composer.fill("Unsent draft");
  await app.screenshot("paused-goal-with-draft");
  await expect(screen.getByRole("button", "Resume goal")).toBeVisible();
  await expect(screen.getByRole("button", "Clear goal")).toBeVisible();
  await screen.getByRole("button", "Resume goal").tap();
  await pause(threadId, false);
  await app.screenshot("resumed-goal-keeps-draft");
  await expect(composer).toHaveValue("Unsent draft");
  await pause(threadId);
  await screen.getByText("Goal paused", { exact: false }).first().waitFor({ timeout: 120_000 });
  await screen.getByRole("button", "Clear goal").tap();
  await expect(screen.getByText("Goal paused", { exact: false })).not.toBeVisible();
  await expect(composer).toHaveValue("Unsent draft");
  await app.screenshot("cleared-goal-keeps-draft");
});
