import * as fs from "node:fs/promises";
import * as path from "node:path";
import * as Effect from "effect/Effect";
import { ThreadId } from "@t3tools/contracts";
import { expect } from "e2e";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, runPromise, rpcClient, test, WEB } from "./t3.ts";

test("Goal usage and native subagent status use Japanese duration units", WEB, async ({t3,app,screen,browser}) => {
 if(!process.env.DURATION_REPLAY_BINARY)throw new Error("Set DURATION_REPLAY_BINARY to the native replay driver");
 const project=await t3.project("duration-demo");
 const placeholder=await t3.thread({project,title:"Japanese durations",messages:["Start"]});
 const settingsPath=path.join(T3_HOME,"userdata/settings.json");
 const settings=JSON.parse(await fs.readFile(settingsPath,"utf8"));
 settings.providerInstances.codex={driver:"codex",enabled:true,config:{binaryPath:process.env.DURATION_REPLAY_BINARY}};
 await fs.writeFile(settingsPath,JSON.stringify(settings));
 await t3.open("/settings/general");
 await screen.getByLabel("Language",{exact:true}).tap();
 await screen.getByText("日本語",{exact:true}).tap();
 await screen.getByLabel("言語",{exact:true}).waitFor();
 const {cli}=makeState(T3_HOME);
 let launched="";
 await expect.poll(async()=>{
 const r=await runPromise(cli(["thread","start",project,"Spawn two subagents to inspect package.json and tsconfig.json.","--provider","codex","--model","gpt-5.6-luna","--title","Duration verification","--wait","--json"],[0,1,2])).catch(()=>undefined);
 if(r?.stdout.includes('threadId')) launched=r.stdout;
 return launched.length>0;
 },{timeout:60000}).toBe(true);
 const {threadId}=JSON.parse(launched);
 await t3.open({threadId});
 await screen.getByText("Verify Japanese duration units",{exact:true}).waitFor({timeout:60000});
 await screen.getByText("メッセージを同期しています...",{exact:false}).waitFor({state:"hidden"});
 await app.screenshot("goal-usage-japanese");
 // Open the recorded native child through the CLI's family view.
 const family=await runPromise(Effect.gen(function*(){
 const client=yield* rpcClient(T3_HOME,app.baseUrl??"");
 return yield* client["orchestration.getThreadFamily"]({threadId:ThreadId.make(threadId)});
 }).pipe(Effect.scoped));
 const child=family.threads.find(t=>t.lineage.relationshipToParent==="subagent")?.id;
 if(!child) throw new Error("No native child in thread family");
 await t3.open({threadId:child});
 await screen.getByText(/^完了 \(\d.*(?:秒|s)\)$/).waitFor({timeout:30000});
 await app.screenshot("subagent-status-japanese");
 const subagentText=await browser.locator("body").textContent();
 await t3.open({threadId});
 await expect(screen.getByText(/2分5秒/)).toBeVisible();
 expect(subagentText).not.toMatch(/完了[^\n]*\d+s/);
});
