import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import { ProviderDriverKind, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";
import { run } from "./shell.ts";
// Real Pi CLI recordings: session header and assistant record; only cwd is redacted.
const recordings = {
  "root": [
    {
      "type": "session",
      "version": 3,
      "id": "01a23e72-e00e-7444-a0a2-a3b9828f6ee6",
      "timestamp": "2026-12-04T00:27:25.584Z",
      "cwd": "[redacted project path]"
    },
    {
      "type": "message",
      "id": "4a9c26e1",
      "parentId": "27a20279",
      "timestamp": "2026-12-04T00:27:27.866Z",
      "message": {
        "role": "assistant",
        "content": [
          {
            "type": "text",
            "text": "ok"
          }
        ],
        "api": "anthropic-messages",
        "provider": "anthropic",
        "model": "claude-haiku-5-5",
        "usage": {
          "input": 2,
          "output": 4,
          "cacheRead": 0,
          "cacheWrite": 2528,
          "totalTokens": 2534,
          "cost": {
            "input": 2.0000000000000002e-07,
            "output": 2e-06,
            "cacheRead": 0,
            "cacheWrite": 0.0005056,
            "total": 0.0005078000000000001,
            "totalFromProvider": false
          },
          "cacheWrite1h": 2528,
          "reasoning": 0
        },
        "stopReason": "stop",
        "timestamp": 1796344045687,
        "providerThinkingLevel": "medium",
        "responseId": "msg_011Chfjk6F4J6H4jn1h3PVpW",
        "rawStopReason": "end_turn",
        "durationMs": 2179,
        "thinkingLevel": "medium"
      }
    }
  ],
  "control": [
    {
      "type": "session",
      "version": 3,
      "id": "01a23e73-5790-719c-be25-90ecec01641c",
      "timestamp": "2026-12-04T00:27:56.178Z",
      "cwd": "[redacted project path]"
    },
    {
      "type": "message",
      "id": "a419c062",
      "parentId": "e0b43e46",
      "timestamp": "2026-12-04T00:28:03.122Z",
      "message": {
        "role": "assistant",
        "content": [
          {
            "type": "text",
            "text": "ok"
          }
        ],
        "api": "anthropic-messages",
        "provider": "anthropic",
        "model": "claude-sonnet-5",
        "usage": {
          "input": 2,
          "output": 4,
          "cacheRead": 0,
          "cacheWrite": 2502,
          "totalTokens": 2508,
          "cost": {
            "input": 4e-06,
            "output": 4e-05,
            "cacheRead": 0,
            "cacheWrite": 0.010008,
            "total": 0.010052,
            "totalFromProvider": false
          },
          "cacheWrite1h": 2502,
          "reasoning": 0
        },
        "stopReason": "stop",
        "timestamp": 1796344076286,
        "responseId": "msg_011ChfjnLFyTdniKPY8StsUq",
        "rawStopReason": "end_turn",
        "durationMs": 6836,
        "thinkingLevel": "medium"
      }
    }
  ],
  "worktree": [
    {
      "type": "session",
      "version": 3,
      "id": "01a23e73-9865-7654-99ac-79f871f71aa1",
      "timestamp": "2026-12-04T00:28:12.774Z",
      "cwd": "[redacted project path]"
    },
    {
      "type": "message",
      "id": "057dc803",
      "parentId": "fd21dc25",
      "timestamp": "2026-12-04T00:28:13.773Z",
      "message": {
        "role": "assistant",
        "content": [
          {
            "type": "text",
            "text": "ok"
          }
        ],
        "api": "anthropic-messages",
        "provider": "anthropic",
        "model": "claude-haiku-5-5",
        "usage": {
          "input": 2,
          "output": 4,
          "cacheRead": 2528,
          "cacheWrite": 0,
          "totalTokens": 2534,
          "cost": {
            "input": 2.0000000000000002e-07,
            "output": 2e-06,
            "cacheRead": 2.5280000000000002e-05,
            "cacheWrite": 0,
            "total": 2.748e-05,
            "totalFromProvider": false
          },
          "cacheWrite1h": 0,
          "reasoning": 0
        },
        "stopReason": "stop",
        "timestamp": 1796344092857,
        "providerThinkingLevel": "medium",
        "responseId": "msg_011ChfjoYyyzdSQ61FoF6oFe",
        "rawStopReason": "end_turn",
        "durationMs": 915,
        "thinkingLevel": "medium"
      }
    }
  ],
  "symlink": [
    {
      "type": "session",
      "version": 3,
      "id": "01a23e73-9d6b-77d7-9f15-ffde568527a2",
      "timestamp": "2026-12-04T00:28:14.061Z",
      "cwd": "[redacted project path]"
    },
    {
      "type": "message",
      "id": "2c04562b",
      "parentId": "ba1d15b9",
      "timestamp": "2026-12-04T00:28:15.022Z",
      "message": {
        "role": "assistant",
        "content": [
          {
            "type": "text",
            "text": "ok"
          }
        ],
        "api": "anthropic-messages",
        "provider": "anthropic",
        "model": "claude-haiku-5-5",
        "usage": {
          "input": 2,
          "output": 4,
          "cacheRead": 2528,
          "cacheWrite": 0,
          "totalTokens": 2534,
          "cost": {
            "input": 2.0000000000000002e-07,
            "output": 2e-06,
            "cacheRead": 2.5280000000000002e-05,
            "cacheWrite": 0,
            "total": 2.748e-05,
            "totalFromProvider": false
          },
          "cacheWrite1h": 0,
          "reasoning": 0
        },
        "stopReason": "stop",
        "timestamp": 1796344094141,
        "providerThinkingLevel": "medium",
        "responseId": "msg_011ChfjoeXrALq9RutKRbyTs",
        "rawStopReason": "end_turn",
        "durationMs": 881,
        "thinkingLevel": "medium"
      }
    }
  ],
  "deleted": [
    {
      "type": "session",
      "version": 3,
      "id": "01a23e73-a2a6-73eb-976b-db6f96949fa5",
      "timestamp": "2026-12-04T00:28:15.400Z",
      "cwd": "[redacted project path]"
    },
    {
      "type": "message",
      "id": "9789511a",
      "parentId": "00a82201",
      "timestamp": "2026-12-04T00:28:16.374Z",
      "message": {
        "role": "assistant",
        "content": [
          {
            "type": "text",
            "text": "ok"
          }
        ],
        "api": "anthropic-messages",
        "provider": "anthropic",
        "model": "claude-haiku-5-5",
        "usage": {
          "input": 2,
          "output": 4,
          "cacheRead": 2528,
          "cacheWrite": 0,
          "totalTokens": 2534,
          "cost": {
            "input": 2.0000000000000002e-07,
            "output": 2e-06,
            "cacheRead": 2.5280000000000002e-05,
            "cacheWrite": 0,
            "total": 2.748e-05,
            "totalFromProvider": false
          },
          "cacheWrite1h": 0,
          "reasoning": 0
        },
        "stopReason": "stop",
        "timestamp": 1796344095495,
        "providerThinkingLevel": "medium",
        "responseId": "msg_011ChfjokHdKvdAo3R9tsKnQ",
        "rawStopReason": "end_turn",
        "durationMs": 879,
        "thinkingLevel": "medium"
      }
    }
  ]
};

test("Pi relative history includes project, worktree, symlink and retained deleted history", WEB, async ({t3,app,screen,browser}) => {
 const project = await t3.project("Pi history proof");
 const seed = makeState(T3_HOME);
 const deleted = await seed.state.project("Removed project history");
 const linked = path.join(T3_HOME,"real","nested-project");
 await fs.mkdir(linked,{recursive:true});
 await fs.writeFile(path.join(linked,"README.md"),"Symlink target\n");
 await runPromise(run("git",["init","--quiet","--initial-branch=main"],{cwd:linked}));
 await runPromise(run("git",["add","README.md"],{cwd:linked}));
 await runPromise(run("git",["-c","user.name=Scenario","-c","user.email=scenario@example.invalid","commit","--quiet","-m","Initial"],{cwd:linked}));
 const {cli} = seed;
 const aliasParent = path.join(T3_HOME,"aliases");
 await fs.mkdir(aliasParent,{recursive:true});
 const alias = path.join(aliasParent,"project-link");
 await fs.symlink(linked,alias);
 // Keep only the alias registered, so canonicalisation of ../ is necessary.

 await runPromise(cli(["project","add",alias,"--title","Symlinked project"]));
 await runPromise(Effect.gen(function*(){
   const client = yield* rpcClient(T3_HOME,app.baseUrl);
   yield* client.subscribeServerConfig({}).pipe(Stream.filter(event=>{
     const providers=event.type==="snapshot"?event.config.providers:event.type==="providerStatuses"?event.payload.providers:[];
     return providers.some(p=>p.instanceId==="devReplay"&&p.models.some(m=>m.slug==="multi-turn"));
   }),Stream.runHead);
 }).pipe(Effect.scoped,Effect.timeout("30 seconds")));
 const started = JSON.parse((await runPromise(cli(["thread","start",project,"Reply ok","--worktree","main","--branch","proof-worktree","--provider","devReplay","--model","multi-turn","--wait","--json"]))).stdout);
 const worktree = await runPromise(Effect.gen(function*(){
   const client = yield* rpcClient(T3_HOME,app.baseUrl);
   const result = yield* client["orchestration.getThreadProjection"]({threadId:ThreadId.make(started.threadId)});
   return result.thread.worktreePath!;
 }).pipe(Effect.scoped));
 const control = path.join(T3_HOME,"control-history");
 const entries = [
   [path.join(project,".pi-history "),recordings.root],
   [path.join(worktree,".pi-history "),recordings.worktree],
   [path.join(deleted,".pi-history "),recordings.deleted],
   [path.join(path.dirname(linked),".pi-symlink-history "),recordings.symlink],
   [control,recordings.control],
 ] as const;
 for(const [dir,lines] of entries){
   await fs.mkdir(dir,{recursive:true});
   await fs.writeFile(path.join(dir,"session.jsonl"),lines.map(x=>JSON.stringify(x)).join("\n")+"\n");
 }
 await runPromise(cli(["project","remove",deleted,"--force"]));
 await runPromise(Effect.gen(function*(){
   const client = yield* rpcClient(T3_HOME,app.baseUrl);
   for(const [id,args] of [["pi","--session-dir '.pi-history '"],["pi-symlink","--session-dir '../.pi-symlink-history '"]] as const){
     yield* client["server.updateSettings"]({patch:{},providerInstanceMutation:{operation:"upsert",instanceId:ProviderInstanceId.make(id),instance:{driver:ProviderDriverKind.make("pi"),enabled:true,usageAccess:"allowed",config:{binaryPath:"pi",launchArgs:args},environment:[{name:"PI_CODING_AGENT_SESSION_DIR",value:control,sensitive:false}]}}});
   }
 }).pipe(Effect.scoped));
 await t3.open({threadId:started.threadId});
 const listing = `import json, pathlib, hashlib
entries = ${JSON.stringify(entries.map(([dir],i)=>[dir,["<project>/.pi-history /session.jsonl","<worktree>/.pi-history /session.jsonl","<deleted-project>/.pi-history /session.jsonl","<real-parent>/.pi-symlink-history /session.jsonl","<control>/session.jsonl"][i]]))}
print("REAL PI JSONL FILES ON THIS COMMIT (same recordings on both sides)")
for directory,label in entries:
 p=pathlib.Path(directory)/"session.jsonl"
 data=p.read_bytes()
 rows=[json.loads(x) for x in data.decode().splitlines()]
 usage=rows[-1]["message"]["usage"]
 print(label)
 print("  exists=%s tokens=%s sha256=%s" % (p.is_file(),usage["totalTokens"],hashlib.sha256(data).hexdigest()[:16]))
print("SOURCE FILES VERIFIED")
`;
 await fs.writeFile(path.join(project,"proof-list.py"),listing);
 await runPromise(Effect.gen(function*(){
   const client=yield* rpcClient(T3_HOME,app.baseUrl);
   const input={threadId:started.threadId,terminalId:"Source transcripts"};
   yield* client["terminal.open"]({...input,cwd:project,cols:120,rows:20,env:{PS1:"$ ",PROMPT_COMMAND:""}});
   yield* client["terminal.write"]({...input,data:"export PS1='$ '; unset PROMPT_COMMAND; clear; python3 proof-list.py\r"});
   yield* client["terminal.observe"](input).pipe(Stream.filter(e=>e.type==="snapshot"?e.snapshot.history.includes("SOURCE FILES VERIFIED"):e.type==="output"&&e.data.includes("SOURCE FILES VERIFIED")),Stream.runHead);
 }).pipe(Effect.scoped,Effect.timeout("20 seconds")));
 await screen.getByRole("button","Toggle terminal drawer").tap();
 await screen.getByRole("textbox","Terminal input",{exact:true}).waitFor();
 // Wait for the terminal canvas to paint its real output and become stable before capture.
 await browser.evaluate(async()=>{
   (document.activeElement as HTMLElement|null)?.blur();
   let prior="";
   for(let i=0;i<20;i++){
     const canvas=document.querySelector('canvas') as HTMLCanvasElement|null;
     if(canvas){
       const context=canvas.getContext("2d");
       const pixels=context?.getImageData(0,0,canvas.width,canvas.height).data;
       let ink=0;
       if(pixels) for(let j=0;j<pixels.length;j+=4) if(pixels[j]!<100&&pixels[j+1]!<100&&pixels[j+2]!<100) ink++;
       const current=JSON.stringify(Array.from(context!.getImageData(0,0,canvas.width,Math.min(canvas.height,180*window.devicePixelRatio)).data));
       if(ink>1000&&current===prior) return true;
       prior=current;
     }
     await new Promise(resolve=>setTimeout(resolve,500));
   }
   throw new Error("Terminal listing did not finish painting");
 });
 await app.screenshot("source-jsonl-files");
 await screen.getByRole("button","Toggle terminal drawer").tap();
 await screen.getByRole("button","Usage",{exact:true}).tap();
 const usage=screen.getByRole("dialog","Usage");
 await usage.getByRole("button","Tokens",{exact:true}).tap();
 await usage.getByRole("button","anthropic/claude-sonnet-5",{exact:true}).waitFor();
 await usage.getByRole("button","Refresh usage",{exact:true}).tap();
 await browser.locator('button[aria-label="Refresh usage"]:not(:disabled):visible').waitFor();
 await app.screenshot("pi-history-present");
 // Warm scan above must retain the history after the worktree directory disappears.
 await runPromise(run("git",["worktree","remove","--force",worktree],{cwd:project}));
 await usage.getByRole("button","Refresh usage",{exact:true}).tap();
 await browser.locator('button[aria-label="Refresh usage"]:not(:disabled):visible').waitFor();
 await app.screenshot("pi-history-after-worktree-removal");
 // A single assertion on the missing history; Sonnet stays the same on both sides.
 await expect(usage.getByRole("button","anthropic/claude-haiku-5-5",{exact:true})).toBeVisible();
 await expect(usage.getByText("5 sessions",{exact:true}).first()).toBeVisible();
 await runPromise(cli(["project","remove",alias,"--force"]));
});
