import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { randomUUID } from "node:crypto";
// See docs/internals/mobile-development.md#measuring-renders.
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeWS from "@effect/platform-node/NodeWS";
import {
  CommandId,
  EnvironmentId,
  ExecutionEnvironmentDescriptor,
  ORCHESTRATION_PROTOCOL_HEADER,
  ORCHESTRATION_PROTOCOL_VERSION,
  OrchestrationV2ShellSnapshot,
  ProjectId,
  ProviderInstanceId,
  ThreadId,
  WsRpcGroup,
  type OrchestrationV2ThreadProjection,
} from "@t3tools/contracts";
import * as Console from "effect/Console";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { Command, Flag } from "effect/cli";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
import { RpcClient, RpcSerialization } from "effect/rpc";
import { Socket } from "effect/socket";

const RenderReport = Schema.Struct({
  commits: Schema.Number,
  totalRenders: Schema.Number,
  components: Schema.Array(Schema.Struct({ key: Schema.String, count: Schema.Number })),
  causes: Schema.Array(Schema.Struct({ key: Schema.String, count: Schema.Number })),
});
type RenderReport = typeof RenderReport.Type;
const decodeReport = Schema.decodeUnknownEffect(Schema.fromJsonString(RenderReport));
const InspectorTargets = Schema.Array(
  Schema.Struct({ appId: Schema.String, webSocketDebuggerUrl: Schema.String }),
);
const CdpReply = Schema.Struct({
  id: Schema.Number,
  result: Schema.optional(
    Schema.Struct({
      result: Schema.optional(Schema.Struct({ value: Schema.optional(Schema.Unknown) })),
      exceptionDetails: Schema.optional(Schema.Unknown),
    }),
  ),
});
const decodeCdpReply = Schema.decodeUnknownOption(Schema.fromJsonString(CdpReply));
const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));

class MeasureError extends Schema.TaggedError<MeasureError>()("MeasureError", {
  message: Schema.String,
}) {}

const STREAM_PROMPT =
  "Think it through step by step, then write a 3000-word essay on the history of typesetting in plain paragraphs with a few headings. Do not use any tools.";

interface Options {
  readonly server: string;
  readonly token: string;
  readonly metro: string;
  readonly scheme: string;
  readonly runs: number;
  readonly windowSeconds: number;
  readonly provider: string;
  readonly model: string;
  readonly projectRoot: string;
}

const uuid = Effect.flatMap(SecureRandom.SecureRandom, (random) => random.uuidV4());

const median = (values: ReadonlyArray<number>) => {
  const sorted = [...values].sort((a, b) => a - b);
  const middle = Math.floor(sorted.length / 2);
  return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2;
};

const connectInspector = Effect.fn("measure.connectInspector")(function* (metro: string) {
  const http = yield* HttpClient.HttpClient;
  const targets = yield* http
    .get(`${metro}/json/list`)
    .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(InspectorTargets)));
  const target = targets.find((entry) => entry.appId.startsWith("com.t3tools.t3code"));
  if (!target)
    return yield* new MeasureError({ message: `No T3 Code app is attached to Metro at ${metro}.` });
  // Expo closes inspector sockets unless Origin matches Metro's advertised URL; pass that URL as --metro.
  const socket = yield* Socket.makeWebSocket(target.webSocketDebuggerUrl, {
    headers: { origin: new URL(metro).origin },
    openTimeout: "10 seconds",
  });
  const writer = yield* socket.writer;
  const reader = yield* socket.reader;
  let nextId = 0;
  return Effect.fn("measure.evaluate")(function* (expression: string) {
    const id = ++nextId;
    yield* writer.write(
      encodeJson({ id, method: "Runtime.evaluate", params: { expression, returnByValue: true } }),
    );
    while (true) {
      for (const frame of yield* reader.pull) {
        const text = typeof frame === "string" ? frame : new TextDecoder().decode(frame);
        const reply = decodeCdpReply(text);
        if (Option.isNone(reply) || reply.value.id !== id) continue;
        if (reply.value.result?.exceptionDetails)
          return yield* new MeasureError({
            message: `Evaluation failed: ${encodeJson(reply.value.result.exceptionDetails)}`,
          });
        return reply.value.result?.result?.value;
      }
    }
  });
});

const connectServer = Effect.fn("measure.connectServer")(function* (options: Options) {
  const http = (yield* HttpClient.HttpClient).pipe(
    HttpClient.mapRequest((request) =>
      request.pipe(
        HttpClientRequest.bearerToken(options.token),
        HttpClientRequest.setHeader(
          ORCHESTRATION_PROTOCOL_HEADER,
          String(ORCHESTRATION_PROTOCOL_VERSION),
        ),
      ),
    ),
    HttpClient.filterStatusOk,
  );
  const descriptor = yield* http
    .get(`${options.server}/.well-known/t3/environment`)
    .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(ExecutionEnvironmentDescriptor)));
  const shell = yield* http
    .get(`${options.server}/api/orchestration/shell`)
    .pipe(Effect.flatMap(HttpClientResponse.schemaBodyJson(OrchestrationV2ShellSnapshot)));
  let projectId = shell.projects.find(
    (project) => project.workspaceRoot === options.projectRoot,
  )?.id;
  // A project record outlives its folder, and turns fail without it.
  yield* (yield* FileSystem.FileSystem).makeDirectory(options.projectRoot, { recursive: true });
  if (!projectId) {
    projectId = ProjectId.make(yield* uuid);
    yield* http.execute(
      HttpClientRequest.post(`${options.server}/api/projects/mutate`).pipe(
        HttpClientRequest.bodyJsonUnsafe({
          type: "project.create",
          commandId: yield* uuid,
          projectId,
          title: "Render measurement",
          workspaceRoot: options.projectRoot,
        }),
      ),
    );
  }
  const ticket = yield* http
    .execute(HttpClientRequest.post(`${options.server}/api/auth/websocket-ticket`))
    .pipe(
      Effect.flatMap(HttpClientResponse.schemaBodyJson(Schema.Struct({ ticket: Schema.String }))),
    );
  // 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(
          `${options.server.replace(/^http/, "ws")}/ws?orchestrationProtocol=${ORCHESTRATION_PROTOCOL_VERSION}&wsTicket=${encodeURIComponent(ticket.ticket)}`,
        ),
      ),
      Layer.provide(RpcSerialization.layerJson),
    ),
  );
  const client = yield* RpcClient.make(WsRpcGroup).pipe(Effect.provideContext(protocol));
  return { client, environmentId: EnvironmentId.make(descriptor.environmentId), projectId };
});


const mode = process.argv[2];
const options = {
 server: process.env.PROOF_SERVER!, token: readFileSync(process.env.PROOF_TOKEN_FILE!, "utf8").trim(),
 metro: process.env.PROOF_METRO!, projectRoot: process.env.PROOF_PROJECT!,
 scheme: "t3code-dev", runs: 3, windowSeconds: 2.5, provider: "devReplay", model: "multi-turn",
};
const outfile = process.env.PROOF_RESULT ?? process.env.PROOF_OUT!;
const program = Effect.gen(function* () {
 const {client, environmentId, projectId} = yield* connectServer(options);
 const dispatch = (payload: object) => client["orchestration.dispatchCommand"]({ commandId: randomUUID(), ...payload } as never);
 if (mode === "seed") {
  const parent = ThreadId.make(randomUUID()); const other = ThreadId.make(randomUUID());
  for (const [threadId,title] of [[parent,"Parent"],[other,"Other"]] as const) {
   yield* dispatch({type:"thread.create",createdBy:"user",creationSource:"mobile",threadId,projectId,title, modelSelection:{instanceId:"devReplay", model:"multi-turn"}, runtimeMode:"approval-required",interactionMode:"default",branch:null,worktreePath:null});
  }
  writeFileSync(outfile, JSON.stringify({environmentId, projectId, parent,other},null,2));
  yield* Console.log("Created synthetic Parent and Other threads."); return;
 }
 const state = JSON.parse(readFileSync(process.env.PROOF_STATE!,"utf8"));
 if (mode === "delegate") {
  yield* dispatch({type:"thread.metadata.update",threadId:state.parent,title:"Parent"});
  yield* dispatch({type:"message.dispatch",createdBy:"user",creationSource:"mobile",threadId:state.parent,messageId:randomUUID(),text:"Synthetic parent turn",attachments:[],dispatchMode:{type:"start_immediately"}});
  const p = yield* client["orchestration.getThreadProjection"]({threadId:state.parent});
  const r=p.runs.at(-1)!;
  yield* dispatch({type:"delegated_task.request",createdBy:"user",creationSource:"mobile",parentThreadId:state.parent,parentRunId:r.id,parentNodeId:r.rootNodeId,task:"Synthetic child turn",title:"Delegated child",modelSelection:{instanceId:"devReplay",model:"multi-turn"},runtimeMode:"approval-required",interactionMode:"default"});
  yield* Effect.sleep("8 seconds");
  const after = yield* client["orchestration.getThreadProjection"]({threadId:state.parent});
  const child = after.subagents.at(-1)?.childThreadId;
  if (!child) return yield* new MeasureError({message:"No delegated child created"});
  writeFileSync(process.env.PROOF_STATE!,JSON.stringify({...state,child},null,2));
  yield* Console.log(JSON.stringify({child, parentStatus:after.runs.at(-1)?.status}));return;
 }
 if (mode === "hold-child") {
  yield* dispatch({type:"message.dispatch",createdBy:"user",creationSource:"mobile",threadId:state.child,messageId:randomUUID(),text:"Wait for a fixture choice",attachments:[],modelSelection:{instanceId:"devReplay",model:"question"},dispatchMode:{type:"start_immediately"}});
  const waiting=yield* client["orchestration.subscribeThread"]({threadId:state.child}).pipe(
   Stream.mapEffect(item=>item.kind === "snapshot" && item.projection ? Effect.succeed(item.projection) : client["orchestration.getThreadProjection"]({threadId:state.child})),
   Stream.filter(p=>p.runtimeRequests.some(r=>r.status === "pending")),Stream.runHead,Effect.timeout("45 seconds"));
  yield* Console.log(JSON.stringify({waiting:Option.isSome(waiting),child:state.child})); return;
 }
 if (mode === "delegation-state") {
  const parent=yield* client["orchestration.getThreadProjection"]({threadId:state.parent});
  const child=yield* client["orchestration.getThreadProjection"]({threadId:state.child});
  yield* Console.log(JSON.stringify({parent:{id:parent.thread.id,title:parent.thread.title,archivedAt:parent.thread.archivedAt,runs:parent.runs.map(r=>r.status)},child:{id:child.thread.id,title:child.thread.title,lineage:child.thread.lineage,runs:child.runs.map(r=>r.status),requests:child.runtimeRequests.map(r=>({kind:r.kind,status:r.status}))},other:state.other}));return;
 }
 if (mode === "archive" || mode === "unarchive") { yield* dispatch({type:`thread.${mode}`,threadId:state.parent}); return; }
 const evaluate = yield* connectInspector(options.metro);
 if (mode === "transition") {
  const action=process.argv[3]!;
  const before=JSON.parse(String(yield* evaluate("JSON.stringify(__sidebarProofInspect())")));
  yield* evaluate("__sidebarProofReset(); __t3RenderCounterStart()");
  yield* dispatch(action === "stop-child" ? {type:"thread.stop",threadId:state.child} : {type:`thread.${action}`,threadId:state.parent});
  yield* Effect.sleep("2500 millis");
  const after=JSON.parse(String(yield* evaluate("JSON.stringify(__sidebarProofInspect())")));
  const home=JSON.parse(String(yield* evaluate("JSON.stringify(__sidebarProof)")));
  yield* evaluate("__t3RenderCounterStop()");
  const p=yield* client["orchestration.getThreadProjection"]({threadId:state.parent});
  const result={side:process.env.PROOF_SIDE,sha:process.env.PROOF_SHA,action,before,after,home,parentArchived:p.thread.archivedAt !== null};
  writeFileSync(outfile,JSON.stringify(result,null,2));yield* Console.log(JSON.stringify(result));return;
 }
 if (mode === "pair") {
  const text=readFileSync(process.env.PROOF_PAIR_FILE!,"utf8");
  const url=/Pair URL:\s*(\S+)/.exec(text)![1];
  const query=new URLSearchParams({pairingUrl:url,autoConnect:"1"});
  yield* evaluate(`__t3RenderCounterOpen(${JSON.stringify(`t3code-dev://connections/new?${query}`)})`); return;
 }
 if (mode === "eval") { yield* Console.log(yield* evaluate(process.argv[3]!)); return; }
 if (mode === "open") {
  yield* evaluate(`__t3RenderCounterOpen(${JSON.stringify(`t3code-dev://threads/${environmentId}/${(process.env.PROOF_TARGET === "child" ? state.child : state.parent)}`)})`);
  return;
 }
 if (mode === "status") { yield* Console.log(yield* evaluate("JSON.stringify(__sidebarProof)")); return; }
 const batches = [];
 for (let batch=0;batch<3;batch++) {
  const samples=[];
  for (let i=0;i<15;i++) {
   yield* evaluate("__sidebarProofReset(); __t3RenderCounterStart()");
   const title = `Other ${batch+1}-${i+1}`;
   yield* dispatch({type:"thread.metadata.update",threadId:state.other,title});
   yield* Effect.sleep("2500 millis");
   const home = JSON.parse(String(yield* evaluate("JSON.stringify(__sidebarProof)")));
   const counter = JSON.parse(String(yield* evaluate("JSON.stringify(__t3RenderCounterStop())")));
   const clientShells = JSON.parse(String(yield* evaluate("JSON.stringify(__sidebarProofShells())")));
   if (clientShells.find((s:any)=>s.id===state.other)?.title !== title) return yield* new MeasureError({message:"Renamed shell did not reach mobile client"});
   if (home.marker !== process.env.PROOF_SHA) return yield* new MeasureError({message:"Wrong source marker"});
   const projection = yield* client["orchestration.getThreadProjection"]({threadId: state.other});
   const sample = {batch:batch+1,step:i+1,title,persistedTitle:projection.thread.title,clientShells,home,counter};
   samples.push(sample);
   yield* Console.log(JSON.stringify({batch:batch+1,step:i+1,renders:home.renders,commits:home.commits.length,ms:home.commits.reduce((s:any,c:any)=>s+c.duration,0),marker:home.marker,selection:home.selection,row:home.row,title:projection.thread.title}));
  }
  batches.push(samples);
  writeFileSync(outfile,JSON.stringify({side:process.env.PROOF_SIDE,sha:process.env.PROOF_SHA,platform:process.env.PROOF_PLATFORM ?? "iOS 27.2 iPhone 18 Pro portrait development Hermes",windowMs:2500,batches},null,2));
 }
}).pipe(Effect.scoped,Effect.provide(Layer.mergeAll(NodeServices.layer,NodeCrypto.layer,NodeHttpClient.layerUndici,NodeWS.layerWebSocketConstructor)));
NodeRuntime.runMain(program);
