import { createServer } from 'node:http';
import type { AddressInfo } from 'node:net';
import { fileURLToPath } from 'node:url';
import { afterAll, describe, expect, it } from 'vitest';
import { ManualClock, OfficeRuntime, buildServer, loadOffice, silentLogger } from '@pixeloffice/server';
import pixelofficePi, { type Io } from '../src/extension.ts';
import type { PiApi, PiContext, PiEvent, PiEventName } from '../src/types.ts';

const DEMO = fileURLToPath(new URL('../../../offices/demo/', import.meta.url));
const closers: (() => Promise<unknown>)[] = [];
afterAll(async () => {
  while (closers.length) await closers.pop()!();
});

// Фейковый pi: только подписки.
function makePi() {
  const handlers = new Map<string, (event: PiEvent, ctx: PiContext) => unknown>();
  const pi = {
    on: (event: PiEventName, handler: (event: PiEvent, ctx: PiContext) => unknown) => {
      handlers.set(event, handler);
      return () => handlers.delete(event);
    },
  } as unknown as PiApi;
  return { pi, fire: (event: PiEvent, ctx: PiContext) => handlers.get(event.type)?.(event, ctx) };
}

const ctx = (sessionId: string): PiContext => ({
  cwd: '/x/PixelOffice',
  mode: 'tui',
  sessionManager: { getCwd: () => '/x/PixelOffice', getSessionId: () => sessionId, getSessionName: () => undefined },
});

describe('pixeloffice-pi против сервера', () => {
  it('события pi регистрируют агента и ведут его статусы', async () => {
    const rt = new OfficeRuntime({ office: loadOffice(DEMO), clock: new ManualClock(), log: silentLogger });
    const srv = await buildServer({ runtime: rt, viewerTokens: ['demo-viewer-token'], viewerDist: null, assetsDir: null, testMode: null });
    await srv.app.listen({ port: 0, host: '127.0.0.1' });
    closers.push(() => srv.app.close());
    const url = `http://127.0.0.1:${(srv.app.server.address() as AddressInfo).port}`;

    const { pi, fire } = makePi();
    // tmux «прочитан, ручного имени нет» — детерминированно, без настоящего tmux
    const io: Io = {
      env: { TMUX_PANE: '%5' },
      now: () => new Date(),
      fetch,
      tmux: async () => null,
      config: () => ({ targets: [{ url, token: 'demo-hook-token' }] }),
    };
    pixelofficePi(pi, io);

    await fire({ type: 'session_start', reason: 'startup' }, ctx('sid-1'));
    expect(rt.registry.get('agent:p1:PixelOffice:%5')).toMatchObject({ kind: 'agent', ownerId: 'p1', project: 'PixelOffice', slot: '%5' });
    expect(rt.store.get('agent:p1:PixelOffice:%5')?.status).toBe('idle');

    await fire({ type: 'before_agent_start', messageType: 'user', systemPromptOptions: { sections: {} } }, ctx('sid-1'));
    expect(rt.store.get('agent:p1:PixelOffice:%5')?.status).toBe('working');

    await fire({ type: 'message_end', message: { role: 'assistant', content: 'Готово.\n\n**Вопрос:** едем дальше?' } }, ctx('sid-1'));
    await fire({ type: 'agent_settled', aborted: false }, ctx('sid-1'));
    expect(rt.store.get('agent:p1:PixelOffice:%5')?.status).toBe('needs_input');

    await fire({ type: 'session_shutdown', reason: 'quit' }, ctx('sid-1'));
    expect(rt.store.get('agent:p1:PixelOffice:%5')?.status).toBe('offline');
  });

  it('сервер молчит — ошибка проглочена и быстро', async () => {
    const hang = createServer(() => {}); // принимает соединение и не отвечает
    await new Promise<void>((r) => hang.listen(0, '127.0.0.1', r));
    closers.push(() => new Promise((r) => hang.close(r)));
    const { pi, fire } = makePi();
    const io: Io = {
      env: { TMUX_PANE: '%5' },
      now: () => new Date(),
      fetch,
      tmux: async () => null,
      config: () => ({ targets: [{ url: `http://127.0.0.1:${(hang.address() as AddressInfo).port}`, token: 'demo-hook-token' }] }),
    };
    pixelofficePi(pi, io);
    const t0 = Date.now();
    await expect(fire({ type: 'session_start', reason: 'startup' }, ctx('sid-2'))).resolves.toBeUndefined();
    expect(Date.now() - t0).toBeLessThan(2000); // таймаут запроса 1 с
  });
});
