import { describe, expect, it } from 'vitest';
import pixelofficePi, { defaultIo, type Io } from '../src/extension.ts';
import { QUESTION_RULE } from '../src/question.ts';
import type { PiApi, PiContext, PiEvent, PiEventName } from '../src/types.ts';
import type { Event } from '@pixeloffice/protocol';

type Handler = (event: PiEvent, ctx: PiContext) => unknown;

// Фейковый pi: помнит подписки, события раздаёт вручную.
function makePi() {
  const handlers = new Map<string, Handler>();
  const pi = {
    on: (event: PiEventName, handler: Handler) => {
      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: PiContext = {
  cwd: '/Users/stas/Projects/My/PixelOffice',
  mode: 'tui',
  sessionManager: { getCwd: () => '/Users/stas/Projects/My/PixelOffice', getSessionId: () => 'sid-7', getSessionName: () => 'Делаю адаптер pi' },
};

// Io с собирающим fetch; tmux по умолчанию «прочитан, метки нет», конфиг есть, время фиксировано.
function makeIo(opts: { env?: Record<string, string>; tmux?: Io['tmux']; config?: Io['config'] } = {}) {
  const batches: Event[][] = [];
  const io: Io = {
    env: opts.env ?? { TMUX_PANE: '%21' },
    now: () => new Date('2026-10-30T12:00:00.000Z'),
    fetch: (async (_url: URL | string, init?: RequestInit) => {
      batches.push(JSON.parse(String(init?.body)).events);
      return new Response('{"accepted":1}', { status: 200 });
    }) as typeof fetch,
    tmux: opts.tmux ?? (async () => null),
    config: opts.config ?? (() => ({ targets: [{ url: 'http://office', token: 't' }] })),
  };
  return { io, batches };
}

describe('жизненный цикл сессии pi', () => {
  it('старт → idle, промпт и ходы → working, оседание → idle, выключение → offline', async () => {
    const { pi, fire } = makePi();
    const { io, batches } = makeIo();
    pixelofficePi(pi, io);
    const agent = { project: 'PixelOffice', slot: '%21' }; // projectDir на сервер не уходит (гигиена relay)

    await fire({ type: 'session_start', reason: 'startup' }, CTX);
    expect(batches.at(-1)).toEqual([{ type: 'status', agent, status: 'idle', at: '2026-10-30T12:00:00.000Z', ttlSec: 43_200, label: { text: 'Делаю адаптер pi', private: true } }]);

    const sections: Record<string, string> = {};
    await fire({ type: 'before_agent_start', messageType: 'user', systemPromptOptions: { sections } }, CTX);
    expect(sections['pixeloffice']).toBe(QUESTION_RULE); // правило о метке вопроса — в промпте
    expect(batches.at(-1)).toEqual([{ type: 'status', agent, status: 'working', at: '2026-10-30T12:00:00.000Z', ttlSec: 900, label: { text: 'Делаю адаптер pi', private: true } }]);

    await fire({ type: 'turn_end' }, CTX);
    expect(batches.at(-1)![0]).toMatchObject({ status: 'working' });

    await fire({ type: 'message_end', message: { role: 'assistant', content: 'Готово.' } }, CTX);
    expect(batches.length).toBe(3); // текст только запомнили — в сеть не шли

    await fire({ type: 'agent_settled', aborted: false }, CTX);
    expect(batches.at(-1)).toEqual([{ type: 'status', agent, status: 'idle', at: '2026-10-30T12:00:00.000Z', ttlSec: 43_200, label: { text: 'Делаю адаптер pi', private: true } }]);

    await fire({ type: 'session_shutdown', reason: 'quit' }, CTX);
    expect(batches.at(-1)![0]).toMatchObject({ status: 'offline' });
  });

  it('ход кончился вопросом с меткой → needs_input и облачко с вопросом', async () => {
    const { pi, fire } = makePi();
    const { io, batches } = makeIo();
    pixelofficePi(pi, io);
    await fire({ type: 'before_agent_start', messageType: 'user', systemPromptOptions: { sections: {} } }, CTX);
    await fire({ type: 'message_end', message: { role: 'assistant', content: 'Сделал.\n\n**Вопрос:** берём вариант 2?' } }, CTX);
    await fire({ type: 'agent_settled', aborted: false }, CTX);
    expect(batches.at(-1)!.map((e) => (e.type === 'status' ? e.status : e.type))).toEqual(['needs_input', 'bubble']);
    expect(batches.at(-1)![1]).toMatchObject({ text: 'берём вариант 2?', ttlSec: 3600 });
  });

  it('прерванный ход (Escape) — idle, вопрос из старого ответа не всплывает', async () => {
    const { pi, fire } = makePi();
    const { io, batches } = makeIo();
    pixelofficePi(pi, io);
    await fire({ type: 'before_agent_start', messageType: 'user', systemPromptOptions: { sections: {} } }, CTX);
    await fire({ type: 'message_end', message: { role: 'assistant', content: '**Вопрос:** так?' } }, CTX);
    await fire({ type: 'agent_settled', aborted: true }, CTX);
    expect(batches.at(-1)).toMatchObject([{ type: 'status', agent: expect.anything(), status: 'idle', at: expect.any(String) }]);
  });

  it('блокирующий диалог в ходе: needs_input с заголовком, ответ — working, оседание — idle', async () => {
    const { pi, fire } = makePi();
    const { io, batches } = makeIo();
    pixelofficePi(pi, io);
    await fire({ type: 'before_agent_start', messageType: 'user', systemPromptOptions: { sections: {} } }, CTX);
    await fire({ type: 'ui_prompt_start', kind: 'select', title: 'Какой вариант?' }, CTX);
    expect(batches.at(-1)!.map((e) => (e.type === 'status' ? e.status : e.type))).toEqual(['needs_input', 'bubble']);
    expect(batches.at(-1)![1]).toMatchObject({ text: 'Какой вариант?', ttlSec: 3600 });

    await fire({ type: 'ui_prompt_end', kind: 'select', title: 'Какой вариант?' }, CTX);
    expect(batches.at(-1)![0]).toMatchObject({ status: 'working' });

    await fire({ type: 'agent_settled', aborted: false }, CTX);
    expect(batches.at(-1)![0]).toMatchObject({ status: 'idle' });
  });

  it('диалог вне хода (команда): после ответа — idle; без заголовка — «Нужен ответ»', async () => {
    const { pi, fire } = makePi();
    const { io, batches } = makeIo();
    pixelofficePi(pi, io);
    await fire({ type: 'session_start', reason: 'startup' }, CTX);
    await fire({ type: 'ui_prompt_start', kind: 'confirm' }, CTX);
    expect(batches.at(-1)!.map((e) => (e.type === 'status' ? e.status : e.type))).toEqual(['needs_input', 'bubble']);
    expect(batches.at(-1)![1]).toMatchObject({ text: 'Нужен ответ', ttlSec: 3600 });
    await fire({ type: 'ui_prompt_end', kind: 'confirm' }, CTX);
    expect(batches.at(-1)![0]).toMatchObject({ status: 'idle' });
  });

  it('вложенные диалоги: статус меняется только на внешнем', async () => {
    const { pi, fire } = makePi();
    const { io, batches } = makeIo();
    pixelofficePi(pi, io);
    await fire({ type: 'before_agent_start', messageType: 'user', systemPromptOptions: { sections: {} } }, CTX);
    await fire({ type: 'ui_prompt_start', kind: 'confirm', title: 'Точно?' }, CTX);
    const sent = batches.length;
    await fire({ type: 'ui_prompt_start', kind: 'editor' }, CTX);
    await fire({ type: 'ui_prompt_end', kind: 'editor' }, CTX);
    expect(batches.length).toBe(sent); // внутренний диалог ничего не шлёт
    await fire({ type: 'ui_prompt_end', kind: 'confirm', title: 'Точно?' }, CTX);
    expect(batches.at(-1)![0]).toMatchObject({ status: 'working' });
  });

  it('имя сессии сменилось — переотправляется последний статус; после offline — нет', async () => {
    const { pi, fire } = makePi();
    const { io, batches } = makeIo();
    pixelofficePi(pi, io);
    await fire({ type: 'before_agent_start', messageType: 'user', systemPromptOptions: { sections: {} } }, CTX);
    await fire({ type: 'session_info_changed', name: 'Адаптер pi' }, CTX);
    expect(batches.at(-1)).toMatchObject([{ type: 'status', agent: expect.anything(), status: 'working', at: expect.any(String), label: { text: 'Адаптер pi', private: true } }]);

    await fire({ type: 'session_shutdown', reason: 'quit' }, CTX);
    const sent = batches.length;
    await fire({ type: 'session_info_changed', name: 'X' }, CTX);
    expect(batches.length).toBe(sent);
  });

  it('ответ с блоками контента собирается в текст', async () => {
    const { pi, fire } = makePi();
    const { io, batches } = makeIo();
    pixelofficePi(pi, io);
    await fire({ type: 'message_end', message: { role: 'assistant', content: [{ type: 'text', text: '**Вопрос:**' }, { type: 'text', text: 'едем?' }] } }, CTX);
    await fire({ type: 'agent_settled', aborted: false }, CTX);
    expect(batches.at(-1)![1]).toMatchObject({ type: 'bubble', text: 'едем?' });
  });
});

describe('метка и окружение', () => {
  it('ручное имя окна tmux — метка статусов, имя сессии не запасной', async () => {
    const { pi, fire } = makePi();
    const { io, batches } = makeIo({ tmux: async () => ({ text: 'pi adapter', private: false }) });
    pixelofficePi(pi, io);
    await fire({ type: 'session_start', reason: 'startup' }, CTX);
    expect(batches.at(-1)![0]).toMatchObject({ label: { text: 'pi adapter', private: false } });
  });

  it('tmux не ответил — поля label нет, прежняя метка на сервере остаётся', async () => {
    const { pi, fire } = makePi();
    const { io, batches } = makeIo({ tmux: async () => undefined });
    pixelofficePi(pi, io);
    await fire({ type: 'session_start', reason: 'startup' }, CTX);
    expect('label' in batches.at(-1)![0]!).toBe(false);
  });

  it('вне tmux (нет TMUX_PANE) слот — id сессии, метка — имя сессии', async () => {
    const { pi, fire } = makePi();
    const { io, batches } = makeIo({ env: {} });
    pixelofficePi(pi, io);
    await fire({ type: 'session_start', reason: 'startup' }, CTX);
    expect(batches.at(-1)![0]).toMatchObject({ agent: { slot: 'sid-7' }, label: { text: 'Делаю адаптер pi', private: true } });
  });

  it('офис не настроен — событий нет, правило в промпт не попадает', async () => {
    const { pi, fire } = makePi();
    const { io, batches } = makeIo({ config: () => null });
    pixelofficePi(pi, io);
    const sections: Record<string, string> = {};
    await fire({ type: 'before_agent_start', messageType: 'user', systemPromptOptions: { sections } }, CTX);
    await fire({ type: 'agent_settled', aborted: false }, CTX);
    expect(sections['pixeloffice']).toBeUndefined();
    expect(batches).toHaveLength(0);
  });

  it('print-прогон (одноразовый) ничего не шлёт и правило в промпт не кладёт — даже в панели tmux', async () => {
    const { pi, fire } = makePi();
    const { io, batches } = makeIo();
    pixelofficePi(pi, io);
    const printCtx: PiContext = { ...CTX, mode: 'print' };
    const sections: Record<string, string> = {};
    await fire({ type: 'session_start', reason: 'startup' }, printCtx);
    await fire({ type: 'before_agent_start', messageType: 'user', systemPromptOptions: { sections } }, printCtx);
    await fire({ type: 'agent_settled', aborted: false }, printCtx);
    await fire({ type: 'session_shutdown', reason: 'quit' }, printCtx);
    expect(sections['pixeloffice']).toBeUndefined();
    expect(batches).toHaveLength(0);
  });

  it('сервер недоступен — ошибка проглочена, сессия не страдает', async () => {
    const { pi, fire } = makePi();
    const io: Io = {
      ...defaultIo,
      env: { TMUX_PANE: '%1' },
      fetch: (async () => Promise.reject(new Error('network'))) as typeof fetch,
      tmux: async () => null,
      config: () => ({ targets: [{ url: 'http://127.0.0.1:1', token: 't' }] }),
    };
    pixelofficePi(pi, io);
    await expect(fire({ type: 'session_start', reason: 'startup' }, CTX)).resolves.toBeUndefined();
  });
});
