import { mkdtempSync } from 'node:fs';
import type { AddressInfo } from 'node:net';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import type { ServerMessage } from '@pixeloffice/protocol';
import { AtlasStore, buildServer, collectFrames, ManualClock, OfficeRuntime, renderScenario } from '../src/index.ts';

const renderScenarioHello = async (...a: Parameters<typeof renderScenario>) => (await renderScenario(...a))[0];
import { demoOffice, makeRuntime, miniAssets } from './helpers.ts';

const office = demoOffice();
const closers: (() => Promise<unknown>)[] = [];
afterEach(async () => {
  while (closers.length) await closers.pop()!();
});

describe('тестовый режим', () => {
  it('morning: два агента проекта demo — «Стас · demo» и «Стас · demo 2» (спека агентов §3.3)', async () => {
    const h = await renderScenarioHello(office, { scenario: 'morning', t: '60000', seed: '1' });
    expect(h.entities.filter((e) => e.kind === 'agent').map((e) => [e.id, e.label])).toEqual([
      ['agent:p1:demo:%1', 'Стас · demo'],
      ['agent:p1:demo:%2', 'Стас · demo 2'],
    ]);
  });

  it('agents20: в каждом из 5 проектов номера 1–4', async () => {
    const h = await renderScenarioHello(office, { scenario: 'agents20', t: '60000', seed: '1' });
    const labels = h.entities.filter((e) => e.kind === 'agent').map((e) => e.label).sort();
    const expected = ['demo', 'api', 'site', 'infra', 'docs'].flatMap((p) => [`Стас · ${p}`, `Стас · ${p} 2`, `Стас · ${p} 3`, `Стас · ${p} 4`]).sort();
    expect(labels).toEqual(expected);
  });

  it('sit4: четыре человека сидят в четырёх направлениях; результат детерминирован', async () => {
    // p1 и p2 demo — на машинах (спека транспорта 4.5.1): выходят у двери машины после парковки, вторая ждёт замка;
    // p2 садится около 44 с, к 30 с оба ещё в пути.
    const q = { scenario: 'sit4', t: '60000', seed: '1' };
    const h = await renderScenarioHello(office, q);
    expect(h.test).toBe(true);
    const facings = Object.fromEntries(h.characters.map((c) => [c.id, [c.facing, c.pose]]));
    // p1 и p2 — в своих кабинках (место хозяина p1 над столом, p2 — под), p3 и p4 — боковые кресла переговорки m1.
    expect(facings).toEqual({ p1: ['down', 'sit'], p2: ['up', 'sit'], p3: ['right', 'sit'], p4: ['left', 'sit'] });
    const m1 = new Set(h.map.spots.filter((s) => s.zoneId === 'meeting:m1').map((s) => `${s.x},${s.y}`));
    expect(h.characters.filter((c) => m1.has(`${c.x},${c.y}`)).map((c) => c.id).sort()).toEqual(['p3', 'p4']);
    // Сидящий лицом к зрителю за столом кабинки — с подписью над головой (место с label: above); остальные без поля.
    const labels = Object.fromEntries(h.characters.map((c) => [c.id, c.label]));
    expect(labels).toEqual({ p1: 'above', p2: undefined, p3: undefined, p4: undefined });
    expect(await renderScenarioHello(office, q)).toEqual(h);
  });

  it('meeting9: девять человек в большой переговорке', async () => {
    // Ирина (p9) на машине (спека транспорта 4.5.1) паркуется последней и садится около 64 с.
    const h = await renderScenarioHello(office, { scenario: 'meeting9', t: '70000', seed: '1' });
    const m2 = h.map.spots.filter((s) => s.zoneId === 'meeting:m2').map((s) => `${s.x},${s.y}`);
    const seated = h.characters.filter((c) => m2.includes(`${c.x},${c.y}`));
    expect(seated).toHaveLength(9);
  });

  it('queue-full: к 15 с семь агентов с живыми вопросами — пять карточек и счётчик на снимке (спека предела очереди 4.4)', async () => {
    const h = await renderScenarioHello(office, { scenario: 'queue-full', t: '15000', seed: '1' });
    expect(h.characters.filter((c) => c.bubble?.kind === 'needs_input')).toHaveLength(7);
  });

  it('lounge: вслед за hello — debug с бронями мест на тот же момент (отладочный слой, спека 7)', async () => {
    const q = { scenario: 'lounge', t: '40000', seed: '1' };
    const [hello, debug] = await renderScenario(office, q);
    expect(hello).toEqual(await renderScenarioHello(office, q));
    expect(debug.type).toBe('debug');
    const spots = new Set(hello.map.spots.map((s) => s.id));
    const reserved = Object.keys(debug.reservations);
    expect(reserved.length).toBeGreaterThan(0);
    expect(reserved.every((id) => spots.has(id))).toBe(true);
  });

  it('addressed: me=p1 видит личное и «всем», me=p2 — только «всем», без me — всё; owner = me (спека адресных сообщений 2.5.1)', async () => {
    // t = 30 с: на 15 с в кадре ещё нет ни p3 (автобус, bus.wait 10 с — входит после ~16 с), ни p1 (паркуется дольше) —
    // ожидания невыполнимы; ttl всех сообщений 3600 с — к 30 с пузыри живы, все адресаты в кадре.
    const q = { scenario: 'addressed', t: '30000', seed: '1' } as Record<string, string>;
    const bubbles = async (me?: string) =>
      Object.fromEntries(
        (await renderScenarioHello(office, me ? { ...q, me } : q))
          .characters.flatMap((c) => (c.bubble ? [[c.id, c.bubble.text]] : [])),
      );
    expect(await bubbles('p1')).toEqual({ p2: 'Задеплоила статику, посмотри сайт', p3: 'Обед в час на кухне — все', 'agent:p1:demo:%1': 'Тесты зелёные, можно деплоить' });
    expect(await bubbles('p2')).toEqual({ p3: 'Обед в час на кухне — все' });
    expect(Object.keys(await bubbles())).toHaveLength(3); // без me — без фильтрации: существующие скриншоты не ломаются
    expect((await renderScenarioHello(office, { ...q, me: 'p1' })).owner).toBe('p1');
  });

  it('по WebSocket с renderScenario: hello и debug, без дельт', async () => {
    const { rt } = makeRuntime();
    const srv = await buildServer({ runtime: rt, viewerTokens: ['demo-viewer-token'], viewerDist: null, assetsDir: null, ingest: false, testMode: (q) => renderScenario(office, q) });
    await srv.app.listen({ port: 0, host: '127.0.0.1' });
    closers.push(() => srv.app.close());
    const port = (srv.app.server.address() as AddressInfo).port;
    const got: ServerMessage[] = [];
    const ws = new WebSocket(`ws://127.0.0.1:${port}/v1/ws?token=demo-viewer-token&scenario=lounge&t=40000&seed=1`);
    closers.push(async () => ws.close());
    ws.addEventListener('message', (e) => got.push(JSON.parse(String(e.data))));
    await new Promise((r) => setTimeout(r, 500));
    expect(got.map((m) => m.type)).toEqual(['hello', 'debug']);
  });

  it('неизвестный сценарий и t вне диапазона — ошибка', async () => {
    await expect(renderScenarioHello(office, { scenario: 'nope', t: '0' })).rejects.toThrow();
    await expect(renderScenarioHello(office, { scenario: 'sit4', t: '-5' })).rejects.toThrow();
  });

  it('по WebSocket: один hello без дельт; POST /v1/events отсутствует', async () => {
    const { rt } = makeRuntime();
    const srv = await buildServer({
      runtime: rt,
      viewerTokens: ['demo-viewer-token'],
      viewerDist: null,
      assetsDir: null,
      ingest: false,
      testMode: (q) => renderScenarioHello(office, q),
    });
    await srv.app.listen({ port: 0, host: '127.0.0.1' });
    closers.push(() => srv.app.close());
    const port = (srv.app.server.address() as AddressInfo).port;
    const got: ServerMessage[] = [];
    const ws = new WebSocket(`ws://127.0.0.1:${port}/v1/ws?token=demo-viewer-token&scenario=sit4&t=30000&seed=1`);
    closers.push(async () => ws.close());
    ws.addEventListener('message', (e) => got.push(JSON.parse(String(e.data))));
    await new Promise((r) => setTimeout(r, 500));
    expect(got.map((m) => m.type)).toEqual(['hello']);
    const post = await fetch(`http://127.0.0.1:${port}/v1/events`, { method: 'POST', body: '{}', headers: { 'content-type': 'application/json' } });
    expect(post.status).toBe(404);
  });

  it('атлас: renderScenario ждёт готовности — hello со ссылкой /atlas/ (спека атласа 2.4.2)', async () => {
    const plain = new OfficeRuntime({ office, clock: new ManualClock() }).hello();
    const frames = collectFrames(plain.map, plain.vehicleKit ?? null, plain.characterLayout);
    const { assets, sheets } = miniAssets(office.bundle.catalog, frames);
    const atlas = new AtlasStore({ dataDir: mkdtempSync(join(tmpdir(), 'po-atlas-tm-')), assetsDir: assets, catalog: office.bundle.catalog, sheets });
    const h = await renderScenarioHello(office, { scenario: 'morning', t: '0', seed: '1' }, { atlas });
    expect(h.map.floor[0]!.frame.sheet).toMatch(/^\/atlas\/[0-9a-f]{64}\.png$/);
  });
});
