import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeWS from "@effect/platform-node/NodeWS";
import {
  ORCHESTRATION_PROTOCOL_VERSION,
  WsRpcGroup,
} from "@t3tools/contracts";
import { expect } from "e2e";
import * as SecureRandom from "effect/crypto/SecureRandom";
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 { makeState, runPromise, test, WEB } 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, output] = process.argv.slice(2);
const state = makeState(home).state;
const project = await state.project("Skill demo", {
  ".agents/skills/cafe-pr/SKILL.md": "---\nname: cafe-pr\ndescription: Manage pull requests with the cafe CLI.\n---\n# Cafe pull requests\n\nReview the pull request and its checks before merging.\n",
});
const thread = await state.thread({ project, title: "Skill instructions", messages: ["Hello"] });
await runPromise(Effect.gen(function* () {
  const client = yield* rpcClient(home, origin);
  yield* client["server.updateSettings"]({ patch: {}, providerInstanceMutation: {
    operation: "upsert", instanceId: "codex", instance: {
      driver: "codex", enabled: true, config: { binaryPath: "codex" },
    },
  }});
}).pipe(Effect.scoped));
const fs = await import("node:fs/promises");
const environment = await (await fetch(`${origin}/.well-known/t3/environment`)).json();
await fs.writeFile(output, JSON.stringify({ threadPath: `/${environment.environmentId}/${thread.threadId}`, pairingPath: await fs.readFile(`${home}/pairing-path`, "utf8") }));
console.log("Synthetic project and replay thread ready.");
