import { readFileSync, writeFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
import { randomUUID } from "node:crypto";
import { CommandId, ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("Missing worktree emits a settle-script warning only when configured", WEB, async ({t3,app,screen}) => {
  const state = makeState(T3_HOME);
  const cli = (args: string[]) => runPromise(state.cli(args));
  const withScript = await t3.project("WithScript");
  const noScript = await t3.project("NoScript");
  const start = async (project: string, title: string) => {
    const result = JSON.parse((await cli(["thread","start",project,"first","--title",title,"--provider","devReplay","--model","multi-turn","--worktree","main","--wait","--json"])).stdout);
    return JSON.parse((await cli(["thread","show",result.threadId,"--json"])).stdout).thread;
  };
  const missing = await start(withScript,"WithScript removed worktree");
  const scriptless = await start(noScript,"NoScript removed worktree");
  const control = await start(withScript,"Control existing worktree");
  await runPromise(Effect.gen(function*(){
    const rpc = yield* rpcClient(T3_HOME,app.baseUrl!);
    yield* rpc["projects.mutate"]({type:"project.update",commandId:CommandId.make(randomUUID()),projectId:missing.projectId,scripts:[{id:"teardown",name:"Teardown",command:"touch settle-marker",icon:"configure",runOnSettle:true,runOnWorktreeCreate:false}]});
  }).pipe(Effect.scoped));
  for(const thread of [missing,scriptless]) execFileSync("git",["worktree","remove","--force",thread.worktreePath],{cwd:thread===missing?withScript:noScript});
  await t3.open({threadId:missing.threadId});
  const offset = readFileSync(".e2e/app.log","utf8").length;
  await runPromise(Effect.gen(function*(){
    const rpc = yield* rpcClient(T3_HOME,app.baseUrl!);
    for(const thread of [control,scriptless,missing]) yield* rpc["orchestration.dispatchCommand"]({type:"thread.settle",commandId:CommandId.make(randomUUID()),threadId:ThreadId.make(thread.threadId)});
  }).pipe(Effect.scoped));
  // CLI round trips also capture the persisted state after the settle commands.
  const states=[];
  for(const thread of [control,scriptless,missing]) states.push(JSON.parse((await cli(["thread","show",thread.threadId,"--json"])).stdout).thread);
  const log=readFileSync(".e2e/app.log","utf8").slice(offset);
  const warnings=log.split("\n").filter(line=>line.includes("settle script skipped") || line.includes("worktreePath") || line.includes("threadId"));
  const sanitized=warnings.join("\n").replaceAll(T3_HOME,"<scenario-home>");
  writeFileSync((process.env.EVIDENCE_DIR ?? "/tmp")+"/server-evidence-"+(log.includes("settle script skipped")?"head":"base")+".txt",JSON.stringify({controlMarker:execFileSync("test",["-f",control.worktreePath+"/settle-marker"]).toString() === "",threads:states.map((t:any)=>({title:t.title,threadId:t.threadId,status:t.status})),warningCount:log.split("settle script skipped").length-1,warning:sanitized},null,2));
  await app.screenshot("settled-missing-worktree");
  expect(log).toContain("settle script skipped: the thread's worktree no longer exists");
  expect(log).toContain(missing.threadId);
  expect(log).toContain(missing.worktreePath);
  expect(log.split("settle script skipped").length-1).toBe(1);
});
