import { describe, expect, it } from 'vitest';
import { EventsBodySchema } from '@pixeloffice/protocol';
import { PROJECTS, resolveScenarioSource, scenarios, type ScenarioContext, type ScenarioEvent } from '../src/index.ts';

const people = ['p1', 'p2', 'p3', 'p4', 'p5', 'p6', 'p7', 'p8', 'p9'];
const ctx: ScenarioContext = { people, owner: 'p1', seed: 1, baseTime: Date.parse('2026-01-05T09:00:00Z') };

describe('сценарии', () => {
  for (const [name, s] of Object.entries(scenarios)) {
    it(`${name}: события валидны и упорядочены`, () => {
      const evs = s.build(ctx);
      expect(evs.length).toBeGreaterThan(0);
      expect(evs.map((e) => e.atMs)).toEqual([...evs.map((e) => e.atMs)].sort((a, b) => a - b));
      expect(EventsBodySchema.safeParse({ events: evs.map((e) => e.event).slice(0, 500) }).success).toBe(true);
    });
  }

  it('детерминированы по seed', () => {
    expect(scenarios['agents20']!.build(ctx)).toEqual(scenarios['agents20']!.build(ctx));
    expect(scenarios['agents20']!.build({ ...ctx, seed: 2 })).not.toEqual(scenarios['agents20']!.build(ctx));
  });

  it('agents20 — 20 разных панелей', () => {
    const slots = new Set(scenarios['agents20']!.build(ctx).flatMap((e) => (e.event.type !== 'snapshot' && e.event.agent ? [e.event.agent.slot] : [])));
    expect(slots.size).toBe(20);
  });

  it('meeting9: снимок с 9 участниками; меньше 9 людей — ошибка', () => {
    const snap = scenarios['meeting9']!.build(ctx).find((e) => e.event.type === 'snapshot')!;
    expect(snap.event.type === 'snapshot' && snap.event.entities.filter((x) => x.status === 'meeting')).toHaveLength(9);
    expect(() => scenarios['meeting9']!.build({ ...ctx, people: ['p1'] })).toThrow();
  });

  // Слоты по проектам в порядке появления: проект → слоты.
  const slotsByProject = (name: string) => {
    const out: Record<string, string[]> = {};
    for (const e of scenarios[name]!.build(ctx)) {
      if (e.event.type === 'snapshot' || !e.event.agent) continue;
      const slots = (out[e.event.agent.project] ??= []);
      if (!slots.includes(e.event.agent.slot)) slots.push(e.event.agent.slot);
    }
    return out;
  };

  it('проекты агентов: agents20 — 5 проектов по 4 агента, lounge — 5 разных, morning — demo, needs-input — demo, api и site', () => {
    const a20 = slotsByProject('agents20');
    expect(Object.keys(a20).sort()).toEqual([...PROJECTS].sort());
    expect(Object.values(a20).map((s) => s.length)).toEqual([4, 4, 4, 4, 4]);
    const lounge = slotsByProject('lounge');
    expect(Object.keys(lounge).sort()).toEqual([...PROJECTS].sort());
    expect(Object.values(lounge).map((s) => s.length)).toEqual([1, 1, 1, 1, 1]);
    expect(slotsByProject('morning')).toEqual({ demo: ['%1', '%2'] });
    expect(slotsByProject('needs-input')).toEqual({ demo: ['%1'], api: ['%2'], site: ['%3'] });
  });

  it('queue-full: семь агентов с вопросами в пяти проектах — предел очереди на снимке (спека предела очереди 4.4)', () => {
    expect(slotsByProject('queue-full')).toEqual({ demo: ['%1', '%6'], api: ['%2', '%7'], site: ['%3'], infra: ['%4'], docs: ['%5'] });
  });

  it('leave: каждый человек и агенты утра уходят в offline', () => {
    const evs = scenarios['leave']!.build(ctx);
    expect(evs.every((e) => e.event.type === 'status' && e.event.status === 'offline')).toBe(true);
    expect(evs.flatMap((e) => (e.event.type === 'status' && e.event.entityId ? [e.event.entityId] : []))).toEqual(people);
    expect(slotsByProject('leave')).toEqual({ demo: ['%1', '%2'] });
  });

  it('evening: все приходят, в 45 с уходят по одному, в 120 с возвращаются; агенты %1, %2 проекта demo', () => {
    const evs = scenarios['evening']!.build(ctx);
    expect(slotsByProject('evening')).toEqual({ demo: ['%1', '%2'] });
    const of = (id: string) => evs.filter((e) => e.event.type === 'status' && e.event.entityId === id).map((e) => [e.atMs, e.event.type === 'status' ? e.event.status : '']);
    expect(of('p1')).toEqual([[0, 'online'], [45_000, 'offline'], [120_000, 'online']]);
    expect(of('p9')).toEqual([[2400, 'online'], [45_000 + 8 * 700, 'offline'], [128_000, 'online']]);
    const agentOff = evs.filter((e) => e.source === 'agent' && e.event.type === 'status' && e.event.status === 'offline').map((e) => e.atMs);
    expect(agentOff).toEqual([45_000, 45_500]);
  });

  it('addressed: сообщения «человек → человеку» и «всем»; needs-input — адресат у сообщения человека (спека адресных сообщений 2.5.2)', () => {
    const evs = scenarios['addressed']!.build(ctx);
    const toOf = (events: ScenarioEvent[], id: string, atMs: number) => {
      const e = events.find((x) => x.atMs === atMs && x.event.type === 'bubble' && (x.event.entityId ?? '') === id);
      return e && e.event.type === 'bubble' ? e.event.to : undefined;
    };
    expect(toOf(evs, 'p2', 8000)).toEqual(['p1']); // личное хозяину
    expect(toOf(evs, 'p3', 9000)).toBe('all'); // объявление
    expect(toOf(scenarios['needs-input']!.build(ctx), 'p2', 11_000)).toEqual(['p1']); // needs-input: «Кофе…» — адресат, иначе не увидит никто
  });

  it('resolveScenarioSource: агентский — с owner, человеческий — без', () => {
    const sources = [{ source: 'manual', token: 'x'.repeat(8) }, { source: 'claude-hook', token: 'y'.repeat(8), owner: 'p1' }];
    expect(resolveScenarioSource(sources, 'agent')?.source).toBe('claude-hook');
    expect(resolveScenarioSource(sources, 'human')?.source).toBe('manual');
  });

  it('resolveScenarioSource: нет источника без owner — человеческий берётся с humans: true (спека хостинга 10)', () => {
    const only = [{ source: 'colleague', token: 'z'.repeat(8), owner: 'p1', humans: true }];
    expect(resolveScenarioSource(only, 'human')?.source).toBe('colleague');
    expect(resolveScenarioSource(only, 'agent')?.source).toBe('colleague');
    expect(resolveScenarioSource([{ source: 'hook', token: 'y'.repeat(8), owner: 'p1' }], 'human')).toBeUndefined();
  });
});
