import { describe, expect, it } from 'vitest';
import { World, WorldMap, type FrameCharacter, type Rules, type Spot, type Zone } from '../src/index.ts';
import { bundle } from './fixtures.ts';

const b = bundle();
const FAST: Partial<Rules> = { dwellMs: { agent: 0, human: 0 } };
const A = { id: 'agent:a:p:%1', kind: 'agent' as const, ownerId: 'a' };
const A2 = { id: 'agent:a:p:%2', kind: 'agent' as const, ownerId: 'a' };

function world(over: Partial<Rules> = FAST) {
  const w = new World({ map: b.map, rules: { ...b.rules, ...over }, poses: b.catalog.characters.poses });
  w.upsertEntity({ id: 'a', kind: 'human', podZoneId: 'pod:a' });
  w.upsertEntity(A);
  w.upsertEntity(A2);
  return w;
}
const run = (w: World, ms: number) => {
  for (let t = 0; t < ms; t += 50) w.tick(50);
};
const ch = (w: World, id: string) => w.characters().find((c) => c.id === id);
const bubbleIn = (w: World, id: string) => w.drainEvents().changed.find((c) => c.id === id)?.bubble;

describe('World: облачка', () => {
  it('появляется, не дублируется, убирается по ttl', () => {
    const w = world();
    w.setStatus(A.id, 'working');
    run(w, 3000);
    w.drainEvents();
    w.setBubble(A.id, 'Привет', 5);
    expect(bubbleIn(w, A.id)).toEqual({ text: 'Привет', kind: 'info' });
    expect(w.drainEvents().changed).toEqual([]);
    run(w, 5000);
    expect(bubbleIn(w, A.id)).toBeNull();
  });

  it('needs_input: облачко с ?-видом и гаснет, когда статус уходит', () => {
    const w = world();
    w.setStatus(A.id, 'working');
    run(w, 3000);
    w.setStatus(A.id, 'needs_input');
    w.setBubble(A.id, 'Разрешить pnpm test?', 3600);
    expect(bubbleIn(w, A.id)).toEqual({ text: 'Разрешить pnpm test?', kind: 'needs_input' });
    w.setStatus(A.id, 'working');
    run(w, 100);
    expect(bubbleIn(w, A.id)).toBeNull();
  });

  it('needs_input: облачко запроса не гаснет по ttl, пока агент ждёт ответа', () => {
    const w = world();
    w.setStatus(A.id, 'working');
    run(w, 3000);
    w.setStatus(A.id, 'needs_input');
    w.setBubble(A.id, 'Разрешить pnpm test?', 5);
    expect(bubbleIn(w, A.id)).toEqual({ text: 'Разрешить pnpm test?', kind: 'needs_input' });
    run(w, 10_000);
    expect(w.drainEvents().changed).toEqual([]);
    w.setStatus(A.id, 'idle');
    run(w, 100);
    expect(bubbleIn(w, A.id)).toBeNull();
  });

  it('needs_input без облачка: «Ждёт ответа», настоящий текст запроса его заменяет', () => {
    const w = world();
    w.setStatus(A.id, 'working');
    run(w, 3000);
    w.drainEvents();
    w.setStatus(A.id, 'needs_input');
    expect(bubbleIn(w, A.id)).toEqual({ text: 'Ждёт ответа', kind: 'needs_input' });
    w.setBubble(A.id, 'Разрешить pnpm test?', 3600);
    expect(bubbleIn(w, A.id)).toEqual({ text: 'Разрешить pnpm test?', kind: 'needs_input' });
  });

  it('bootstrap: ждущему — сохранённый вопрос с адресатами или «Ждёт ответа» — «всем» (спека адресных сообщений 2.1.7)', () => {
    const w = world();
    w.bootstrap([
      { id: 'a', status: 'online' },
      { id: A.id, status: 'needs_input', question: { text: 'Разрешить pnpm test?', to: ['a'] } },
      { id: A2.id, status: 'needs_input' },
    ]);
    expect(w.questions()).toEqual({
      [A.id]: { text: 'Разрешить pnpm test?', to: ['a'] },
      [A2.id]: { text: 'Ждёт ответа', to: 'all' },
    });
  });

  it('статусное «Ждёт ответа» и адресат облачка-запроса: без события — всем, событие хранит своих адресатов (спека адресных сообщений 2.1.7)', () => {
    const w = world();
    w.setStatus(A.id, 'working');
    run(w, 3000);
    w.drainEvents();
    w.setStatus(A.id, 'needs_input');
    const waiting = w.characters().find((c) => c.id === A.id) as FrameCharacter;
    expect([waiting.bubble?.text, waiting.bubbleTo]).toEqual(['Ждёт ответа', 'all']);
    w.setBubble(A.id, 'Разрешить?', 3600, ['a']);
    expect(w.questions()[A.id]).toEqual({ text: 'Разрешить?', to: ['a'] });
  });

  it('needs_input: облачко запроса гаснет сразу после ответа, не дожидаясь dwell нового статуса', () => {
    const w = world({}); // реальный dwell агента 20 с
    w.setStatus(A.id, 'working');
    run(w, 25_000);
    w.setStatus(A.id, 'needs_input');
    w.setBubble(A.id, 'Разрешить pnpm test?', 3600);
    expect(bubbleIn(w, A.id)).toEqual({ text: 'Разрешить pnpm test?', kind: 'needs_input' });
    w.setStatus(A.id, 'working'); // ответ на запрос
    w.tick(50);
    expect(bubbleIn(w, A.id)).toBeNull();
    expect(w.status(A.id)?.status).toBe('needs_input'); // цель меняется по dwell, как раньше
    w.setBubble(A.id, 'Готово', 10); // облачко после ответа — обычное
    expect(bubbleIn(w, A.id)).toEqual({ text: 'Готово', kind: 'info' });
  });

  it('облачко невидимого персонажа приходит с его появлением', () => {
    const w = world();
    expect(w.setBubble(A.id, 'Готов', 60)).toBe('absent'); // невидимому — absent, облачко хранится до появления (2.1.10)
    w.setStatus(A.id, 'working');
    w.tick(50);
    expect(bubbleIn(w, A.id)).toEqual({ text: 'Готов', kind: 'info' });
  });

  it('результат установки: видимому — ok, невидимому — absent (облачко хранится до появления), незнакомцу — absent', () => {
    const w = world();
    w.setStatus(A.id, 'working');
    run(w, 3000);
    expect(w.setBubble(A.id, 'Привет', 60)).toBe('ok'); // агент на виду
    expect(w.setBubble('a', 'Пока не пришёл', 60)).toBe('absent'); // человек без статуса — невидим
    expect(w.setBubble('nobody', 'нет такого', 60)).toBe('absent'); // персонажа нет в мире
    // Невидимому облачок ставится (спека 2.1.10): придёт с его появлением — это проверяет тест ниже.
    w.setStatus('a', 'online');
    run(w, 6000);
    expect(bubbleIn(w, 'a')).toEqual({ text: 'Пока не пришёл', kind: 'info' });
  });
});

describe('World: bootstrap, правила, прошлые места, отладка', () => {
  it('bootstrap ставит онлайн-сущности сразу на места, офлайн — невидимы', () => {
    const w = world({}); // реальный dwell: bootstrap его не ждёт
    w.bootstrap([
      { id: 'a', status: 'online' },
      { id: A.id, status: 'working' },
      { id: A2.id, status: 'offline' },
    ]);
    expect(ch(w, 'a')).toMatchObject({ x: 1, y: 2, pose: 'sit' });
    expect(ch(w, A.id)).toMatchObject({ x: 2, y: 2, pose: 'sit' });
    expect(ch(w, A2.id)).toBeUndefined();
    expect(w.status(A.id)?.status).toBe('working');
  });

  it('bootstrap встречи: все участники видны сразу, комната выбирается на всех (на 4, а не на 2)', () => {
    const spots: Spot[] = [];
    const add = (zoneId: string, x: number, y: number) =>
      spots.push({ id: `${zoneId}#${x},${y}`, x, y, facing: 'up', pose: 'sit', offset: [0, 0], label: 'below', fidgets: [], tags: [], itemUid: 'x', zoneId });
    [1, 2].forEach((x) => add('meeting:small', x, 1));
    [1, 2, 3, 4].forEach((x) => add('meeting:big', x, 3));
    const zones: Zone[] = [
      { id: 'meeting:small', kind: 'meeting', rect: [0, 0, 10, 2] },
      { id: 'meeting:big', kind: 'meeting', rect: [0, 2, 10, 2] },
    ];
    const map = new WorldMap({ width: 10, height: 6, blocked: new Uint8Array(60), spots, zones, entrances: [[0, 5]] });
    const w = new World({ map, rules: { ...b.rules }, poses: b.catalog.characters.poses });
    const ids = ['h1', 'h2', 'h3'];
    for (const id of ids) w.upsertEntity({ id, kind: 'human' });
    w.bootstrap(ids.map((id) => ({ id, status: 'meeting' as const, meetingId: 'm1' })));
    const pos = ids.map((id) => ch(w, id)!);
    expect(pos.map((p) => p.y)).toEqual([3, 3, 3]);
    expect(new Set(pos.map((p) => `${p.x},${p.y}`)).size).toBe(3);
    expect(w.debugInfo().meetings).toEqual({ m1: ['meeting:big'] });
  });

  it('setRules сразу переназначает цели', () => {
    const w = world();
    w.setStatus('a', 'online');
    w.setStatus(A.id, 'idle');
    run(w, 8000);
    expect(ch(w, A.id)).toMatchObject({ x: 1, y: 5 });
    w.setRules({ ...b.rules, ...FAST, agent: { ...b.rules.agent, idle: [{ kind: 'zone', zoneId: 'coworking', pose: 'sit' }] } });
    run(w, 8000);
    expect(ch(w, A.id)).toMatchObject({ x: 10, y: 2 });
    // решение 13: чьё текущее место и по новым правилам подходит, тот не двигается
    expect(ch(w, 'a')).toMatchObject({ x: 1, y: 2, pose: 'sit' });
  });

  it('прошлые места сохраняются и восстанавливаются', () => {
    const w = world();
    w.setStatus(A.id, 'working');
    run(w, 8000);
    expect(w.lastSeats()).toEqual({ [A.id]: b.map.spotAt(2, 2)!.id });
    const w2 = world();
    w2.restoreLastSeats({ [A.id]: b.map.spotAt(4, 2)!.id, 'agent:ghost': 'нет-такого' });
    w2.setStatus(A.id, 'working');
    run(w2, 8000);
    expect(ch(w2, A.id)).toMatchObject({ x: 4, y: 2 });
  });

  it('debugInfo: путь идущего, брони, переговорки', () => {
    const w = world();
    w.setStatus(A.id, 'working');
    w.tick(50);
    const d = w.debugInfo();
    expect(d.paths[A.id]!.length).toBeGreaterThan(1);
    expect(d.reservations[b.map.spotAt(2, 2)!.id]).toBe(A.id);
    expect(d.meetings).toEqual({});
  });
});

describe('World: цель stay', () => {
  const STAY: Partial<Rules> = { ...FAST, agent: { ...b.rules.agent, needs_input: [{ kind: 'stay' }] } };

  it('идущий персонаж останавливается в ближайшей клетке, не держит бронь и не остаётся в позе ходьбы', () => {
    const w = world(STAY);
    w.setStatus(A.id, 'working');
    run(w, 600); // вышел от входа и идёт к столу
    expect(ch(w, A.id)!.pose).toBe('walk');
    w.setStatus(A.id, 'needs_input');
    run(w, 2000);
    const c = ch(w, A.id)!;
    expect(c).toMatchObject({ pose: 'stand', anim: 'idle' });
    expect(Number.isInteger(c.x) && Number.isInteger(c.y)).toBe(true);
    expect([c.x, c.y]).not.toEqual([2, 2]);
    expect(w.debugInfo().reservations[b.map.spotAt(2, 2)!.id]).toBeUndefined();
  });

  it('сидящий персонаж остаётся на своём месте с бронью', () => {
    const w = world(STAY);
    w.setStatus(A.id, 'working');
    run(w, 8000);
    w.setStatus(A.id, 'needs_input');
    run(w, 2000);
    expect(ch(w, A.id)).toMatchObject({ x: 2, y: 2, pose: 'sit' });
    expect(w.debugInfo().reservations[b.map.spotAt(2, 2)!.id]).toBe(A.id);
  });

  it('невидимый персонаж из очереди появления не держит бронь места', () => {
    const w = world(STAY);
    w.setStatus(A.id, 'working');
    w.setStatus(A2.id, 'working');
    w.tick(50); // A появился, A2 ждёт в очереди с бронью
    w.setStatus(A2.id, 'needs_input');
    run(w, 2000);
    expect(ch(w, A2.id)).toBeUndefined();
    expect(Object.values(w.debugInfo().reservations)).not.toContain(A2.id);
  });
});

describe('World: пересмотр запасных целей', () => {
  it('стоящий в запасной клетке занимает место, как только оно освободилось (без смены статуса)', () => {
    const warns: string[] = [];
    const rules = { ...b.rules, ...FAST, agent: { ...b.rules.agent, working: [{ kind: 'zone' as const, zoneId: 'coworking', pose: 'sit' as const }] } };
    const w = new World({ map: b.map, rules, poses: b.catalog.characters.poses, onWarn: (m) => warns.push(m) });
    const A3 = { id: 'agent:a:p:%3', kind: 'agent' as const, ownerId: 'a' };
    for (const e of [A, A2, A3]) w.upsertEntity(e);
    for (const e of [A, A2, A3]) w.setStatus(e.id, 'working');
    run(w, 10_000);
    expect(ch(w, A3.id)).toMatchObject({ pose: 'stand' }); // коворкинг на 2 места занят
    const warned = warns.length;
    run(w, 20_000);
    expect(warns.length).toBe(warned); // пересмотр не спамит warn
    w.setStatus(A.id, 'offline');
    run(w, 15_000);
    expect(ch(w, A3.id)).toMatchObject({ pose: 'sit' });
  });
});
