import { describe, expect, it } from 'vitest';
import type { FrameCharacter } from '@pixeloffice/core';
import type { Bubble, DeltaMessage, HelloMessage, ServerMessage } from '@pixeloffice/protocol';
import { bubbleVisible, frameForViewer } from '../src/frames.ts';

// Персонаж с облачком и адресатами, как собирает World: фильтрую достаточно «текст есть/нет» — адресаты
// (агент — хозяину, человек — из события) уже решены на стороне мира.
const char = (id: string, text: string, to?: 'all' | string[], kind: Bubble['kind'] = 'info'): FrameCharacter => ({
  id, x: 1, y: 2, facing: 'down', pose: 'sit', anim: 'sit', offset: [0, 0],
  bubble: { text, kind }, // фильтр меняет только видимость текста, kind персонаж задаёт сам
  ...(to !== undefined ? { bubbleTo: to } : {}),
});
const hello = (...characters: FrameCharacter[]): HelloMessage => ({ type: 'hello', protocol: 4, t: 0, test: false, map: {} as HelloMessage['map'], characterLayout: {} as HelloMessage['characterLayout'], avatarKit: {} as HelloMessage['avatarKit'], entities: [], characters });
const delta = (...characters: FrameCharacter[]): DeltaMessage => ({ type: 'delta', t: 0, characters });
// «нет персонажа» — только когда персонажа с таким id в кадре нет; bubble: null («затёрто») должен
// доходить до сравнения как null, поэтому не через `??`, который подменяет и null, и undefined.
const bubbleOf = (m: ServerMessage, id: string) => {
  const c = m.type === 'hello' || m.type === 'delta' ? m.characters.find((c) => c.id === id) : undefined;
  return c === undefined ? 'нет персонажа' : c.bubble;
};

describe('bubbleVisible / frameForViewer (таблица видимости спеки адресных сообщений 2.1.2)', () => {
  // «затёрто» = bubble: null. Облачко агента p1 (хозяин), чужого агента, человека адресату/чужому/без адресата,
  // статусное «Ждёт ответа» и объявление.
  const cases: [string, FrameCharacter, Bubble | null, Bubble | null][] = [
    ['агент, хозяин p1', char('ag1', 'своё', ['p1']), { text: 'своё', kind: 'info' }, null],
    ['агент, чужой хозяин', char('ag2', 'чужое', ['p2']), null, null],
    ['человек, адресовал p1', char('h1', 'тебе', ['p1']), { text: 'тебе', kind: 'info' }, null],
    ['человек, адресовал другого', char('h2', 'не тебе', ['p2']), null, null],
    ['человек, без адресата', char('h3', 'никому'), null, null],
    ['статусное «Ждёт ответа»', char('h4', 'Ждёт ответа', 'all', 'needs_input'), { text: 'Ждёт ответа', kind: 'needs_input' }, { text: 'Ждёт ответа', kind: 'needs_input' }],
    ['to: all', char('h5', 'объявление', 'all'), { text: 'объявление', kind: 'info' }, { text: 'объявление', kind: 'info' }],
  ];
  for (const [name, c, forP1, forShared] of cases) {
    it(`${name}: p1 — ${forP1 ? 'виден' : 'затёрто'}, общий токен — ${forShared ? 'виден' : 'затёрто'}`, () => {
      const h = hello(c);
      expect(bubbleOf(frameForViewer(h, 'p1'), c.id)).toEqual(forP1);
      expect(bubbleOf(frameForViewer(h, null), c.id)).toEqual(forShared);
      const d = delta(c);
      expect(bubbleOf(frameForViewer(d, 'p1'), c.id)).toEqual(forP1);
      expect(bubbleOf(frameForViewer(d, null), c.id)).toEqual(forShared);
    });
  }

  it('hello персональный: owner = person токена; общий и без фильтрации — прежний owner', () => {
    const h = hello(char('h1', 'тебе', ['p1']));
    h.owner = 'от-источников'; // owner? уже есть в HelloMessage
    expect(frameForViewer(h, 'p1').owner).toBe('p1');
    expect(frameForViewer(h, null).owner).toBe('от-источников');
    expect(frameForViewer(h, undefined).owner).toBe('от-источников');
  });

  it('без фильтрации (undefined): видно всё — тестовый режим без me; адресаты срезаются и так', () => {
    const h = frameForViewer(hello(char('h2', 'не тебе', ['p2']), char('h3', 'никому')), undefined);
    expect(h.characters.map((c) => [c.bubble?.text ?? null, 'bubbleTo' in c])).toEqual([['не тебе', false], ['никому', false]]);
  });

  it('bubbleTo не попадает в кадр ни в каком случае; bubble: null и без поля — не трогаются', () => {
    const seen = frameForViewer(hello(char('h1', 'тебе', ['p1']), { ...char('h2', 'x'), bubble: null }), 'p1');
    expect(seen.characters.every((c) => !('bubbleTo' in c))).toBe(true);
    expect(seen.characters.find((c) => c.id === 'h2')?.bubble).toBeNull();
  });

  it('entity/despawn/debug проходят как есть; bubbleVisible — базовые случаи', () => {
    const m: ServerMessage = { type: 'despawn', id: 'x' };
    expect(frameForViewer(m, 'p1')).toBe(m);
    expect(bubbleVisible('all', null)).toBe(true);
    expect(bubbleVisible(['p1'], 'p1')).toBe(true);
    expect(bubbleVisible(['p1'], 'p2')).toBe(false);
    expect(bubbleVisible(['p1'], null)).toBe(false); // общий токен не адресат
    expect(bubbleVisible(undefined, 'p1')).toBe(false); // адресата нет — не видит никто
    expect(bubbleVisible(['p1'], undefined)).toBe(true); // без фильтрации (me нет) — видно всё
    expect(bubbleVisible(undefined, undefined)).toBe(true);
  });
});
