import * as fs from "node:fs/promises";
import * as path from "node:path";
import { expect } from "e2e";
import { MOBILE, MOBILE_T3_HOME as HOME } from "../e2e.config.ts";
import { makeState, runPromise, environmentId, rpcClient } from "./t3.ts";
import * as Effect from "effect/Effect";
import { ThreadId } from "@t3tools/contracts";
import { IOS, test } from "./t3-mobile.ts";

test("iOS goal usage and native subagent status use Japanese duration units", IOS, async ({t3,app,screen,device})=>{
 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");
 await t3.thread({project,title:"Japanese durations",messages:["Start"]});
 const settingsPath=path.join(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));
 const {cli}=makeState(HOME,{T3CODE_PORT:String(MOBILE.serverPort)});
 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);
 const origin=`http://${MOBILE.host}:${MOBILE.serverPort}`;
 const env=await runPromise(environmentId(origin));
 const family=await runPromise(Effect.gen(function*(){const client=yield* rpcClient(HOME,origin);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");
 await app.clearState().catch(()=>{});
 await t3.open();
 await screen.getByText("Duration verification",{exact:false}).first().waitFor({timeout:120000});
 const link=async(url:string)=>{await device.openLink(`t3code-dev://${url}`,{app:"com.t3tools.t3code.dev"});};
 await link("settings/language");
 await screen.getByText("日本語",{exact:true}).tap();
 await link(`threads/${env}/${encodeURIComponent(threadId)}`);
 await screen.getByLabel(/Verify Japanese duration units/).waitFor({timeout:30000});
 await app.screenshot("mobile-goal-usage-japanese");
 await link(`threads/${env}/${encodeURIComponent(child)}`);
 await screen.getByText(/完了.*(?:秒|s)/).waitFor({timeout:30000});
 await app.screenshot("mobile-subagent-status-japanese");

 await expect(screen.getByText(/完了.*分.*秒/)).toBeVisible();
});
