import { describe, expect, it } from 'vitest';
import { EventsBodySchema } from '@pixeloffice/protocol';
import { BACKGROUND_WORKING_TTL, BUBBLE_MAX, mapHook, NEEDS_INPUT_BUBBLE_TTL, STATUS_TTL, type HookInput } from '../src/map.ts';

const NOW = new Date('2026-10-20T10:00:00.000Z');
const ENV = { CLAUDE_PROJECT_DIR: '/Users/x/Projects/PixelOffice', TMUX_PANE: '%17' };
const AGENT = { project: 'PixelOffice', projectDir: '/Users/x/Projects/PixelOffice', slot: '%17' };
const statusOf = (input: HookInput, env: Record<string, string | undefined> = ENV) =>
  mapHook(input, env, NOW).map((e) => (e.type === 'status' ? e.status : e.type));

describe('mapHook — таблица спеки 6.1', () => {
  it.each(['startup', 'resume', 'clear', 'fork'])('SessionStart source=%s → idle', (source) => {
    expect(statusOf({ hook_event_name: 'SessionStart', source })).toEqual(['idle']);
  });

  it('SessionStart source=compact → без изменений', () => {
    expect(statusOf({ hook_event_name: 'SessionStart', source: 'compact' })).toEqual([]);
  });

  it.each(['UserPromptSubmit', 'PostToolUse', 'PostToolUseFailure'])('%s → working', (name) => {
    expect(statusOf({ hook_event_name: name })).toEqual(['working']);
  });

  it('Stop с вопросом-меткой → needs_input + облачко с вопросом', () => {
    const evs = mapHook({ hook_event_name: 'Stop', last_assistant_message: 'Сделал.\n\n**Вопрос:** коммитим?' }, ENV, NOW);
    expect(evs).toEqual([
      { type: 'status', agent: AGENT, status: 'needs_input', at: NOW.toISOString(), ttlSec: STATUS_TTL.needs_input },
      { type: 'bubble', agent: AGENT, text: 'коммитим?', ttlSec: NEEDS_INPUT_BUBBLE_TTL, at: NOW.toISOString() },
    ]);
  });

  it('Stop без метки → idle', () => {
    expect(statusOf({ hook_event_name: 'Stop', last_assistant_message: 'Готово. Что дальше?' })).toEqual(['idle']);
  });

  it('PreToolUse AskUserQuestion → needs_input + облачко с первым вопросом, другие инструменты — ничего', () => {
    const evs = mapHook({ hook_event_name: 'PreToolUse', tool_name: 'AskUserQuestion', tool_input: { questions: [{ question: 'Какой вариант?' }, { question: 'Второй' }] } }, ENV, NOW);
    expect(evs.map((e) => (e.type === 'status' ? e.status : e.type === 'bubble' ? e.text : e.type))).toEqual(['needs_input', 'Какой вариант?']);
    expect(statusOf({ hook_event_name: 'PreToolUse', tool_name: 'Bash' })).toEqual([]);
  });

  it.each(['Claude needs your permission', 'Claude needs your permission.'])('Notification permission_prompt «%s» (диалог AskUserQuestion) → needs_input без облачка', (message) => {
    expect(statusOf({ hook_event_name: 'Notification', notification_type: 'permission_prompt', message })).toEqual(['needs_input']);
  });

  it('длинный вопрос в облачке обрезается до BUBBLE_MAX', () => {
    const evs = mapHook({ hook_event_name: 'Stop', last_assistant_message: `Вопрос: ${'а'.repeat(600)}` }, ENV, NOW);
    expect(evs[1]?.type === 'bubble' && evs[1].text).toHaveLength(BUBBLE_MAX);
  });

  it('Stop с фоновой задачей running → working с ttl простоя: агент ждёт свою задачу', () => {
    const shell = { id: 'b1', type: 'shell', status: 'running', description: 'sleep 20', command: 'sleep 20' };
    expect(mapHook({ hook_event_name: 'Stop', last_assistant_message: 'Запустил.', background_tasks: [shell] }, ENV, NOW)).toEqual([
      { type: 'status', agent: AGENT, status: 'working', at: NOW.toISOString(), ttlSec: BACKGROUND_WORKING_TTL },
    ]);
  });

  it('Stop с задачами не в running, пустым массивом или без поля → idle', () => {
    const done = { id: 'm1', type: 'monitor', status: 'completed' };
    expect(statusOf({ hook_event_name: 'Stop', background_tasks: [done] })).toEqual(['idle']);
    expect(statusOf({ hook_event_name: 'Stop', background_tasks: [] })).toEqual(['idle']);
    expect(statusOf({ hook_event_name: 'Stop' })).toEqual(['idle']);
  });

  it('Stop с вопросом-меткой и фоновой задачей → needs_input: вопрос важнее', () => {
    const running = { id: 'a1', type: 'subagent', status: 'running' };
    expect(statusOf({ hook_event_name: 'Stop', last_assistant_message: '**Вопрос:** ждём?', background_tasks: [running] })).toEqual(['needs_input', 'bubble']);
  });

  it('Stop только с session_crons (/loop, ScheduleWakeup) → idle', () => {
    expect(statusOf({ hook_event_name: 'Stop', background_tasks: [], session_crons: [{ id: 'c1', schedule: '*/5 * * * *', recurring: true }] } as HookInput)).toEqual(['idle']);
  });

  it('Stop → working с фоновой задачей проходит схему протокола', () => {
    const evs = mapHook({ hook_event_name: 'Stop', background_tasks: [{ id: 'b1', type: 'shell', status: 'running' }] }, ENV, NOW);
    expect(EventsBodySchema.safeParse({ events: evs }).success).toBe(true);
  });

  it('ttl статусов (спека 6.1): working 15 мин, idle и needs_input 12 ч; offline и SessionEnd — без срока', () => {
    expect(STATUS_TTL).toEqual({ working: 900, idle: 43_200, needs_input: 43_200 });
    const ttl = (input: HookInput) => mapHook(input, ENV, NOW).find((e) => e.type === 'status')!['ttlSec'];
    expect(ttl({ hook_event_name: 'UserPromptSubmit' })).toBe(STATUS_TTL.working);
    expect(ttl({ hook_event_name: 'Stop' })).toBe(STATUS_TTL.idle);
    expect(ttl({ hook_event_name: 'Notification', notification_type: 'permission_prompt', message: 'Разрешить?' })).toBe(STATUS_TTL.needs_input);
    expect(ttl({ hook_event_name: 'SessionEnd' })).toBeUndefined();
  });

  it('Stop → idle, SessionEnd → offline', () => {
    expect(statusOf({ hook_event_name: 'Stop' })).toEqual(['idle']);
    expect(statusOf({ hook_event_name: 'SessionEnd' })).toEqual(['offline']);
  });

  it.each(['permission_prompt', 'elicitation_dialog', 'elicitation_url_dialog', 'agent_needs_input'])('Notification %s → needs_input + облачко', (t) => {
    const evs = mapHook({ hook_event_name: 'Notification', notification_type: t, message: 'Claude needs your permission to use Bash' }, ENV, NOW);
    expect(evs).toEqual([
      { type: 'status', agent: AGENT, status: 'needs_input', at: NOW.toISOString(), ttlSec: STATUS_TTL.needs_input },
      { type: 'bubble', agent: AGENT, text: 'Claude needs your permission to use Bash', ttlSec: NEEDS_INPUT_BUBBLE_TTL, at: NOW.toISOString() },
    ]);
  });

  it.each(['elicitation_response', 'elicitation_complete'])('Notification %s → working', (t) => {
    expect(statusOf({ hook_event_name: 'Notification', notification_type: t })).toEqual(['working']);
  });

  it.each(['idle_prompt', 'agent_completed', 'auth_success', 'quota_auto_resume_started', 'что-то-новое'])('Notification %s → игнор', (t) => {
    expect(statusOf({ hook_event_name: 'Notification', notification_type: t })).toEqual([]);
  });

  it('облачко без текста — запасной текст; длинный текст обрезается до 500', () => {
    const empty = mapHook({ hook_event_name: 'Notification', notification_type: 'permission_prompt' }, ENV, NOW);
    expect(empty[1]).toMatchObject({ type: 'bubble', text: 'Нужен ответ' });
    const long = mapHook({ hook_event_name: 'Notification', notification_type: 'permission_prompt', message: 'я'.repeat(900) }, ENV, NOW);
    expect(long[1]?.type === 'bubble' && long[1].text.length).toBe(500);
  });

  it('события субагента (agent_id) засчитываются родителю', () => {
    const evs = mapHook({ hook_event_name: 'PostToolUse', agent_id: 'sub-1', session_id: 's1' }, ENV, NOW);
    expect(evs).toEqual([{ type: 'status', agent: AGENT, status: 'working', at: NOW.toISOString(), ttlSec: STATUS_TTL.working }]);
  });

  it('вне tmux слот — session_id; без CLAUDE_PROJECT_DIR ничего (cwd не годится, спека 4.1); без слота — ничего', () => {
    const evs = mapHook({ hook_event_name: 'Stop', session_id: 'abc-123' }, { CLAUDE_PROJECT_DIR: '/w/Repo/' }, NOW);
    expect(evs[0]).toMatchObject({ agent: { project: 'Repo', projectDir: '/w/Repo/', slot: 'abc-123' } });
    expect(mapHook({ hook_event_name: 'Stop', session_id: 'abc-123', cwd: '/w/Repo/sub' } as HookInput, {}, NOW)).toEqual([]);
    expect(mapHook({ hook_event_name: 'Stop' }, { CLAUDE_PROJECT_DIR: '/w/Repo' }, NOW)).toEqual([]);
  });

  it('неизвестный hook → игнор; результат проходит схему /v1/events', () => {
    expect(statusOf({ hook_event_name: 'SubagentStop' })).toEqual([]);
    const evs = mapHook({ hook_event_name: 'Notification', notification_type: 'permission_prompt', message: 'x' }, ENV, NOW);
    expect(EventsBodySchema.safeParse({ events: evs }).success).toBe(true);
  });
});

describe('mapHook — метка агента (спека метки §3.2)', () => {
  const LABEL = { text: 'tmux names', private: false };
  const labels = (input: HookInput, label?: { text: string; private: boolean } | null) =>
    mapHook(input, ENV, NOW, label).map((e) => [e.type, 'label' in e ? e.label : 'нет поля']);

  it('метка и null попадают в каждое событие status, в том числе needs_input вопроса; в bubble — нет', () => {
    expect(labels({ hook_event_name: 'PostToolUse' }, LABEL)).toEqual([['status', LABEL]]);
    expect(labels({ hook_event_name: 'Stop', last_assistant_message: '**Вопрос:** коммитим?' }, LABEL)).toEqual([
      ['status', LABEL],
      ['bubble', 'нет поля'],
    ]);
    expect(labels({ hook_event_name: 'SessionEnd' }, null)).toEqual([['status', null]]);
    expect(labels({ hook_event_name: 'Stop', background_tasks: [{ status: 'running' }] }, null)).toEqual([['status', null]]);
  });

  it('метка undefined — события как прежде, без поля', () => {
    expect(mapHook({ hook_event_name: 'PostToolUse' }, ENV, NOW, undefined)).toEqual(mapHook({ hook_event_name: 'PostToolUse' }, ENV, NOW));
    expect(labels({ hook_event_name: 'PostToolUse' })).toEqual([['status', 'нет поля']]);
  });

  it('события с меткой проходят схему протокола', () => {
    const events = mapHook({ hook_event_name: 'Stop', last_assistant_message: '**Вопрос:** да?' }, ENV, NOW, LABEL);
    expect(EventsBodySchema.safeParse({ events }).success).toBe(true);
  });
});
