import * as NodeWS from "@effect/platform-node/NodeWS";
import { ORCHESTRATION_PROTOCOL_VERSION, WsRpcGroup } from "@t3tools/contracts";
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 { writeFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { APP_DIR, T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise } from "./t3.ts";

const captureList = async (origin: string) => {
  const state = await runPromise(Effect.gen(function* () {
    const issued = yield* makeState(T3_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),
    );
    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),
    ));
    const client = yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
    return yield* client["device.list"]({});
  }).pipe(Effect.scoped));
  const commit = execFileSync("git", ["rev-parse", "HEAD"], { cwd: APP_DIR, encoding: "utf8" }).trim();
  const warnings = [state.hostStatusDetail, ...Object.values(state.hostStatuses).map((host) => host.detail)].filter(Boolean).join("\n");
  writeFileSync(`${process.env.PROOF_OUTPUT_DIR}/${commit}-device-list.json`, JSON.stringify({
    commit,
    method: "Real server device.list RPC after completing device setup; real expo-device-hub 0.22.1 with stand-in SDK commands.",
    devices: state.devices,
    hostStatus: state.hostStatus,
    avdmanagerWarningRetained: warnings.includes("avdmanager list avd"),
    javaRuntimeWarningRetained: warnings.includes("Unable to locate a Java Runtime"),
  }, null, 2));
};

import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Attached Android tablet survives avdmanager Java failure", WEB, async ({ t3, app, screen }) => {
  const project = await t3.project("Android device discovery");
  const thread = await t3.thread({ project, title: "USB tablet discovery", messages: ["Check the attached Android tablet."] });
  await t3.open(thread);
  await screen.getByRole("button", "Toggle right panel", { exact: true }).tap();
  await screen.getByRole("button", "Device M", { exact: true }).tap();
  await screen.getByRole("switch", "Enable device hub").tap();
  await screen.getByRole("button", "Continue", { exact: true }).tap();
  await screen.getByRole("button", "Continue", { exact: true }).tap();
  await screen.getByRole("button", "Done", { exact: true }).tap();
  await screen.getByRole("button", "Refresh devices", { exact: true }).tap();
  await captureList(app.baseUrl!);
  await app.screenshot("android-device-discovery");
  await expect(screen.getByText("samsung SM-X710", { exact: true })).toBeVisible();
});
