import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
import { formatErrors } from '@pixeloffice/core';
import { buildArenaMap, type ArenaMap } from '../src/arena-map.ts';
import { Match } from '../src/game.ts';
import { FrameHub, type FrameSocket } from '../src/ws-frames.ts';

// Карта local и каталог — как admin.test.ts: абсолютные пути через import.meta.url,
// тест не зависит от cwd.
const LOCAL = fileURLToPath(new URL('../../../offices/local', import.meta.url));
const CATALOG = fileURLToPath(new URL('../../../catalog/limezu/catalog.yaml', import.meta.url));

const loaded = (): { m: Match; arena: ArenaMap } => {
  const built = buildArenaMap(readFileSync(join(LOCAL, 'office.yaml'), 'utf8'), readFileSync(CATALOG, 'utf8'));
  if (!built.ok) throw new Error(formatErrors(built.errors));
  return { m: new Match({ map: built.value.map }), arena: built.value };
};

// Мок сокета (спека push 7.1): интерфейс { send, close, bufferedAmount } без сети.
// Первый close решает — повторные не перезаписывают.
class FakeSocket implements FrameSocket {
  sent: string[] = [];
  closed: { code?: number; reason?: string } | null = null;
  buffered = 0;
  send(data: string): void {
    this.sent.push(data);
  }
  close(code?: number, reason?: string): void {
    this.closed ??= { code, reason };
  }
  get bufferedAmount(): number {
    return this.buffered;
  }
}

describe('FrameHub.broadcast (спека push 4.2)', () => {
  it('после тика кадр ушёл каждому: игроку — свой с self, зрителям — один общий без self', () => {
    const { m, arena } = loaded();
    m.join('a1', 'Аня');
    const hub = new FrameHub();
    const player = new FakeSocket();
    const spec1 = new FakeSocket();
    const spec2 = new FakeSocket();
    hub.add(player, 'a1');
    hub.add(spec1, null);
    hub.add(spec2, null);
    hub.broadcast(m, arena);
    expect(player.sent).toHaveLength(1);
    expect(JSON.parse(player.sent[0]!).self).toBeDefined(); // кадр игрока — как GET state?agent (спека push 3)
    expect(spec1.sent).toHaveLength(1);
    expect(JSON.parse(spec1.sent[0]!).self).toBeUndefined(); // кадр зрителя — как GET state без agent (спека арены 6.4)
    expect(spec2.sent[0]).toBe(spec1.sent[0]); // зрительский кадр сериализуется один на тик (спека push 4.2)
  });

  it('рассылка — сердцебиение: кадр игрока продлевает lastSeenAt (спека арены 6.5, push 3)', () => {
    const { m, arena } = loaded();
    m.join('a1', 'Аня');
    const before = m.agent('a1')!.lastSeenAt;
    m.step();
    const hub = new FrameHub();
    hub.add(new FakeSocket(), 'a1');
    hub.broadcast(m, arena);
    expect(m.agent('a1')!.lastSeenAt).toBeGreaterThan(before);
  });

  it('агента нет — close 1008 unknown_agent и соединение уходит из реестра (спека push 3)', () => {
    const { m, arena } = loaded();
    m.join('a1', 'Аня');
    const hub = new FrameHub();
    const gone = new FakeSocket();
    const ghost = new FakeSocket(); // агента никогда не было: апгрейд без проверки, первый тик закрывает
    hub.add(gone, 'a1');
    hub.add(ghost, 'nope');
    m.leave('a1');
    hub.broadcast(m, arena);
    expect(gone.closed).toEqual({ code: 1008, reason: 'unknown_agent' });
    expect(ghost.closed).toEqual({ code: 1008, reason: 'unknown_agent' });
    expect(gone.sent).toHaveLength(0);
    expect(() => hub.broadcast(m, arena)).not.toThrow(); // закрытые из реестра убраны
  });

  it('closeAll — смена карты: все соединения кодом 1012, реестр пуст (спека push 3, 4.3)', () => {
    const { m, arena } = loaded();
    const hub = new FrameHub();
    const player = new FakeSocket();
    const spec = new FakeSocket();
    hub.add(player, 'a1');
    hub.add(spec, null);
    hub.closeAll(1012, 'arena updated');
    expect(player.closed).toEqual({ code: 1012, reason: 'arena updated' });
    expect(spec.closed).toEqual({ code: 1012, reason: 'arena updated' });
    expect(() => hub.broadcast(m, arena)).not.toThrow(); // рассылать больше некому
  });

  it('backpressure: клиент не читает (bufferedAmount выше лимита) — close без кадра (спека push 3)', () => {
    const { m, arena } = loaded();
    m.join('a1', 'Аня');
    const hub = new FrameHub();
    const slow = new FakeSocket();
    slow.buffered = 2 * 1024 * 1024;
    hub.add(slow, 'a1');
    hub.broadcast(m, arena);
    expect(slow.sent).toHaveLength(0);
    expect(slow.closed).toEqual({ code: 1000, reason: 'backpressure' });
  });

  it('исключение одного соединения не глушит рассылку: виновник close 1011, остальные получают кадры (правка ревью 2026-11-02, находка 4)', () => {
    const { m, arena } = loaded();
    m.join('a1', 'Аня');
    // send бросает — как будущий бросок handleState: рассылка обязана пережить виновника
    class ThrowingSocket extends FakeSocket {
      send(): void {
        throw new Error('send failed');
      }
    }
    const hub = new FrameHub();
    const broken = new ThrowingSocket();
    const healthy = new FakeSocket();
    hub.add(broken, null); // виновник первым в реестре — раньше него кадры не доходили никому
    hub.add(healthy, null);
    expect(() => hub.broadcast(m, arena)).not.toThrow();
    expect(broken.closed).toEqual({ code: 1011, reason: 'broadcast error' });
    expect(healthy.sent).toHaveLength(1); // кадр пришёл, несмотря на бросок первого
    expect(() => hub.broadcast(m, arena)).not.toThrow(); // виновник убран из реестра
    expect(healthy.sent).toHaveLength(2);
  });
});
