import { writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { execFileSync } from 'node:child_process';
import { APP_DIR } from '../e2e.config.ts';
import { randomUUID } from 'node:crypto';
import { CommandId, ThreadId, MessageId, ProviderInstanceId } 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('Stopping a parent preserves completed children and stops active descendants', WEB, async ({t3, app, screen}) => {
  const project = await t3.project('delegation-demo');
  const rpc = async (work: (client: any) => Effect.Effect<any, any, any>) => runPromise(Effect.gen(function*(){
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? '');
    return yield* work(client);
  }).pipe(Effect.scoped) as any);
  const projection = (id: string): Promise<any> => rpc(c => c['orchestration.getThreadProjection']({threadId: ThreadId.make(id)}));
  const dispatch = (command: any) => rpc(c => c['orchestration.dispatchCommand']({...command, commandId: CommandId.make(randomUUID())}));
  const started = await runPromise(makeState(T3_HOME).cli(['thread','start',project,'Delegate the review tasks.','--title','Parent review','--provider','devReplay','--model','showcase','--json']));
  const parent = JSON.parse(started.stdout);
  const delegate = async (id: string, title: string, model: string) => {
    const p = await projection(id);
    const run = p.runs.at(-1);
    await dispatch({type:'delegated_task.request', parentThreadId: id, parentRunId: run.id, parentNodeId: run.rootNodeId, task: title, title, modelSelection:{instanceId:ProviderInstanceId.make('devReplay'),model},runtimeMode:'full-access',interactionMode:'default',completionWake:'settled_only',createdBy:'agent',creationSource:'mcp'});
    const after = await projection(id);
    return after.subagents.at(-1).childThreadId as string;
  };
  const idle = await delegate(parent.threadId, 'Completed review', 'multi-turn');
  const intermediate = await delegate(parent.threadId, 'Intermediate review', 'showcase');
  const grandchild = await delegate(intermediate, 'Active nested review', 'multi-turn');
  const followup = await delegate(parent.threadId, 'Follow-up review', 'multi-turn');
  const wait = async (id: string, status: string) => {
    await expect.poll(async () => (await projection(id)).runs.at(-1)?.status, {timeout:60000}).toBe(status);
  };
  await wait(grandchild,'completed');
  await wait(idle,'completed');
  await wait(intermediate,'completed');
  await wait(followup,'completed');
  await wait(parent.threadId,'completed');
  for (const parentThreadId of [parent.threadId,intermediate]) {
    const p = await projection(parentThreadId);
    for (const task of p.subagents.filter((task:any)=>task.status==='completed')) {
      await dispatch({type:'delegated_task.completion-delivery.acknowledge',parentThreadId,taskId:task.id,observedByRunId:p.runs.at(-1).id});
    }
  }
  const send = (id: string, text: string, createdBy = 'user') => dispatch({type:'message.dispatch',threadId:id,messageId:MessageId.make(randomUUID()),text,attachments:[],dispatchMode:{type:'start_immediately'},modelSelection:{instanceId:ProviderInstanceId.make('devReplay'),model:'question'},createdBy,creationSource:'web'});
  // A scheduled occurrence is background work, so it does not create a follow-up task on its parent.
  const grandchildProjection = await projection(grandchild);
  const scheduled: any = await rpc(c => c['scheduledTasks.upsert']({
    title:'Nested background review', prompt:'Continue the nested review and wait for my answer.',
    enabled:false, schedule:{type:'interval',everyMs:86400000},
    projectId:grandchildProjection.thread.projectId, threadId:grandchild, threadMode:'continue',
    workspaceStrategy:{type:'root'},modelSelection:{instanceId:ProviderInstanceId.make('devReplay'),model:'question'},
    runtimeMode:'full-access',interactionMode:'default'
  }));
  await dispatch({type:'thread.model-selection.set',threadId:grandchild,modelSelection:{instanceId:ProviderInstanceId.make('devReplay'),model:'question'}});
  await rpc(c => c['scheduledTasks.runNow']({id:scheduled.task.id}));
  await wait(grandchild,'running');
  await wait(intermediate,'completed');
  await send(followup,'Continue the review and wait for my answer.');
  await send(parent.threadId,'Continue coordinating the review and wait for my answer.');
  const summarize = async () => {
    const result: Record<string, unknown> = {};
    for (const [name,id] of Object.entries({parent:parent.threadId,idle,intermediate,grandchild,followup})) {
      const p = await projection(id);
      result[name] = {runs:p.runs.map((r:any)=>({status:r.status})), interrupts:p.turnItems.filter((i:any)=>i.type==='run_interrupt_request').map((i:any)=>({title:i.title,message:i.message,type:i.type})), tasks:p.subagents.map((t:any)=>({status:t.status,delivery:t.completionDelivery?.state}))};
    }
    return result;
  };
  const beforeStop = await summarize();
  await t3.open(parent);
  const stop = screen.getByRole('button','Stop generation');
  await stop.waitFor({timeout:60000});
  await app.screenshot('parent-before-stop');
  await stop.tap();
  await stop.waitFor({state:'hidden',timeout:60000});
  await t3.open({threadId:grandchild});
  await screen.getByRole('textbox').waitFor();
  await screen.getByRole('button','Stop generation').waitFor({state:'hidden',timeout:60000});
  await app.screenshot('active-grandchild-stopped');
  await t3.open({threadId:followup});
  await screen.getByRole('textbox').waitFor();
  await screen.getByRole('button','Stop generation').waitFor({state:'hidden',timeout:60000});
  await app.screenshot('direct-followup-stopped');
  await t3.open({threadId:idle});
  await screen.getByRole('textbox').waitFor();
  await screen.getByText('first fixture turn complete', {exact:true}).waitFor();
  await app.screenshot('completed-child-after-parent-stop');
  await t3.open({threadId:intermediate});
  await screen.getByRole('textbox').waitFor();
  await screen.getByText('This turn is a replay.', {exact:false}).waitFor();
  await app.screenshot('intermediate-after-parent-stop');
  const afterStop = await summarize();
  const sha = execFileSync('git',['rev-parse','HEAD'],{cwd:APP_DIR,encoding:'utf8'}).trim();
  await writeFile(join(tmpdir(),'factory-pr-41860-evidence-1',`runtime-${sha}.json`), JSON.stringify({sha,beforeStop,afterStop},null,2));
  expect((await projection(idle)).turnItems.filter((item:any)=>item.type==='run_interrupt_request')).toHaveLength(0);
  expect((await projection(intermediate)).turnItems.filter((item:any)=>item.type==='run_interrupt_request')).toHaveLength(0);
  expect((await projection(grandchild)).runs.at(-1).status).toBe('interrupted');
  expect((await projection(followup)).runs.at(-1).status).toBe('interrupted');
});
