// Run from scripts/scenarios with the isolated T3 home and its web origin as arguments.
import * as NodeWS from "@effect/platform-node/NodeWS";
import { CommandId, ThreadId, 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 { makeState, runPromise } from "./t3.ts";
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 [home, origin] = process.argv.slice(2);
const {state} = makeState(home);
  const project = await state.project("Issue accessibility");
  const thread = await state.thread({project, title: "go", messages: ["go"]});
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(home, origin);
    const projection = yield* client["orchestration.getThreadProjection"]({threadId: ThreadId.make(thread.threadId)});
    yield* client["orchestration.dispatchCommand"]({
      type: "thread.issue.link", commandId: CommandId.make(crypto.randomUUID()),
      threadId: ThreadId.make(thread.threadId), projectId: projection.thread.projectId,
      tracker: "github", host: "github.com", scope: "pingdotgg/t3code", key: "123",
      displayKey: "#123", title: "Sidebar flickers on resize",
      url: "https://github.com/pingdotgg/t3code/issues/123", source: "manual"
    });
  }).pipe(Effect.scoped));

const env = await fetch(origin + "/.well-known/t3/environment").then(r=>r.json());
console.log(JSON.stringify({threadId: thread.threadId, environmentId: env.environmentId, path: `/${env.environmentId}/${thread.threadId}`}));
