import * as NodeCrypto from '@effect/platform-node/NodeCrypto';
import * as fs from 'node:fs/promises';
import * as Effect from 'effect/Effect';
import * as Layer from 'effect/Layer';
import { expect } from 'e2e';
import { APP_DIR, T3_HOME } from '../e2e.config.ts';
import { test, WEB, runPromise } from './t3.ts';

 test('A completed task delegated from another environment settles on its target', WEB, async ({t3, app, screen}) => {
  await t3.project('Delegation proof');
  const settingsPath = `${T3_HOME}/userdata/settings.json`;
  const settings = JSON.parse(await fs.readFile(settingsPath, 'utf8'));
  settings.linkedEnvironmentsEnabled = true;
  await fs.writeFile(settingsPath, JSON.stringify(settings));
  const Auth = await import('../../apps/server/src/auth/EnvironmentAuth.ts');
  const Config = await import('../../apps/server/src/config.ts');
  const Bridge = await import('../../apps/server/src/mcp/AcpMcpStdioBridge.ts');
  const runtime = JSON.parse(await fs.readFile(`${T3_HOME}/userdata/server-runtime.json`, 'utf8'));
  const threadId = await runPromise(Effect.scoped(Effect.gen(function* () {
    const auth = yield* Auth.EnvironmentAuth;
    const issued = yield* auth.issueMcpClientSession({label:'Delegation proof',access:'full-access',peerLink:true,client:{deviceType:'bot'}});
    const session = yield* Bridge.mcpToolSession({endpoint:`${runtime.origin}/mcp`,authorization:`Bearer ${issued.token}`,clientName:'delegation-proof'});
    const call = (name: string, args: Record<string, unknown>) => session.call(name,args).pipe(Effect.map((raw: any) => {
      if(raw.isError) throw new Error(JSON.stringify(raw));
      return raw.structuredContent;
    }));
    const projects = yield* call('t3_project_list',{});
    const launched = yield* call('t3_thread_launch',{
      projectId:projects.projects[0].id,title:'Remote delegated task',
      modelSelection:{instanceId:'devReplay',model:'showcase'},message:'Show the replay demonstration.',
      clientRequestId:'delegate:mcp:parent-on-A:proof',
      delegatedFrom:{environmentId:'environment-elsewhere',threadId:'mcp:parent-on-A',title:'Parent on another environment'}
    });
    yield* Effect.promise(() => t3.open({threadId:launched.threadId}));
    const result = yield* call('t3_thread_wait',{threadId:launched.threadId,timeoutMs:120000});
    console.log('REMOTE_TASK_COMPLETED',JSON.stringify(result));
    return launched.threadId as string;
  }).pipe(Effect.provide(Auth.layerRuntime.pipe(Layer.provide(Config.layerTest(APP_DIR,T3_HOME)), Layer.provide(NodeCrypto.layer))))));
  await screen.getByText('Done', {exact:true}).waitFor({timeout:60000});
  try {
    await expect(screen.getByRole('button', 'Un-settle')).toBeVisible({timeout:90000});
  } finally {
    await screen.getByText('Syncing messages...', {exact:true}).waitFor({state:'hidden',timeout:60000});
    await app.screenshot('remote-task-completed-settlement');
  }
});
