import { describe, expect, it } from 'vitest';
import { agentAvatar, avatarFromKey, defaultProjectAvatar } from '@pixeloffice/core';
import type { AvatarParts } from '@pixeloffice/protocol';
import { EntityRegistry, agentKey } from '../src/index.ts';
import { demoOffice } from './helpers.ts';

const office = demoOffice();
const reg = () => new EntityRegistry(office.bundle.config.people, office.bundle.catalog.characters);
const chars = office.bundle.catalog.characters;
const noneActive = () => false; // никто не активен — номер 1
const T0 = Date.parse('2026-01-05T09:00:00Z');

describe('EntityRegistry', () => {
  const LOOK: AvatarParts = { body: 2, eyes: 3, outfit: [5, 2], hair: [7, 3] };

  it('облик человека: avatars.json → config.yaml → по хешу id (спека редактора §3.2)', () => {
    const { people } = office.bundle.config;
    const overrides = new Map([['p2', LOOK]]);
    const withConfig = new EntityRegistry(people, chars, { people: overrides, projects: new Map() });
    expect(withConfig.get('p2')!.avatar).toEqual(LOOK);
    expect(withConfig.get('p1')!.avatar).toEqual(people[0]!.avatar);
    const bare = new EntityRegistry(people.map(({ avatar: _avatar, ...p }) => p), chars, { people: overrides, projects: new Map() });
    expect(bare.get('p2')!.avatar).toEqual(LOOK);
    expect(bare.get('p1')!.avatar).toEqual(avatarFromKey('p1', chars.pool));
  });

  it('setAvatar меняет облик человека; агента и неизвестного id — нет', () => {
    const r = reg();
    expect(r.setAvatar('p1', LOOK)?.avatar).toEqual(LOOK);
    expect(r.get('p1')!.avatar).toEqual(LOOK);
    const { entity } = r.ensureAgent('p1', { project: 'P', slot: '%1' }, T0, noneActive);
    const before = entity.avatar;
    expect(r.setAvatar(entity.id, LOOK)).toBeUndefined();
    expect(r.get(entity.id)!.avatar).toEqual(before);
    expect(r.setAvatar('nobody', LOOK)).toBeUndefined();
  });

  it('люди из конфига с углами', () => {
    const r = reg();
    expect(r.all()).toHaveLength(9);
    expect(r.isHuman('p1')).toBe(true);
    expect(r.podOf('p8')).toBe('pod:p8');
  });

  it('агент: ключ из хозяина, проекта и слота; имя «хозяин · проект»; облик — облик проекта по «хозяин:проект», не по слоту', () => {
    const r = reg();
    const { entity, created } = r.ensureAgent('p1', { project: 'PixelOffice', projectDir: '/x/PixelOffice', slot: '%17' }, T0, noneActive);
    expect(created).toBe(true);
    expect(entity.id).toBe(agentKey('p1', { project: 'PixelOffice', slot: '%17' }));
    expect(entity.id).toBe('agent:p1:PixelOffice:%17');
    expect(entity.name).toBe('Стас · PixelOffice');
    expect(entity.ordinal).toBe(1);
    expect(entity.avatar).toEqual(defaultProjectAvatar('p1', 'PixelOffice', chars.pool));
    expect(r.ensureAgent('p1', { project: 'PixelOffice', slot: '%17' }, T0 + 1, noneActive).created).toBe(false);
    // Тот же проект в другом слоте (перезапуск tmux, новая сессия) — тот же облик.
    expect(reg().ensureAgent('p1', { project: 'PixelOffice', slot: '%99' }, T0, noneActive).entity.avatar).toEqual(entity.avatar);
  });

  it('удаление по сроку хранения: только офлайн и старше срока', () => {
    const r = reg();
    r.ensureAgent('p1', { project: 'a', slot: '%1' }, T0, noneActive);
    r.ensureAgent('p1', { project: 'b', slot: '%2' }, T0 + 6 * 86_400_000, noneActive);
    const removed = r.removeExpiredAgents(() => true, T0 + 7 * 86_400_000 + 1, 7);
    expect(removed).toEqual(['agent:p1:a:%1']);
    expect(r.removeExpiredAgents(() => false, T0 + 100 * 86_400_000, 7)).toEqual([]);
  });

  describe('номер одновременных агентов проекта (спека агентов §3.3)', () => {
    // Статусы ведёт StatusStore; здесь «активные» — множество id.
    const setup = () => {
      const r = reg();
      const live = new Set<string>();
      const active = (id: string) => live.has(id);
      const start = (slot: string, project = 'pixeloffice', owner = 'p1') => {
        const { entity } = r.ensureAgent(owner, { project, slot }, T0, active);
        live.add(entity.id);
        r.renumber(entity.id, active);
        return entity;
      };
      return { r, live, active, start };
    };

    it('два агента одного проекта — 1 и 2: номер в подписи, у второго сдвиг цвета одежды', () => {
      const { start } = setup();
      const a = start('%1');
      const b = start('%2');
      expect([a.ordinal, b.ordinal]).toEqual([1, 2]);
      expect([a.name, b.name]).toEqual(['Стас · pixeloffice', 'Стас · pixeloffice 2']);
      const project = defaultProjectAvatar('p1', 'pixeloffice', chars.pool);
      expect(a.avatar).toEqual(project);
      expect(b.avatar).toEqual(agentAvatar(project, 2, chars.pool));
    });

    it('первый ушёл в offline — новый получает 1; вернувшийся при занятом номере — наименьший свободный', () => {
      const { r, live, active, start } = setup();
      const a = start('%1');
      const b = start('%2');
      live.delete(a.id); // offline: номер явно не освобождается и не меняется
      const c = start('%3');
      expect([a.ordinal, c.ordinal]).toEqual([1, 1]);
      live.add(a.id);
      expect(r.renumber(a.id, active)).toBe(true);
      expect(a.ordinal).toBe(3);
      expect(a.name).toBe('Стас · pixeloffice 3');
      expect(r.renumber(b.id, active)).toBe(false); // его номер свободен для него самого
      expect(b.ordinal).toBe(2);
    });

    it('хозяева и проекты нумеруются отдельно', () => {
      const { start } = setup();
      expect(start('%1').ordinal).toBe(1);
      expect(start('%2', 'other').ordinal).toBe(1);
      expect(start('%3', 'pixeloffice', 'p2').ordinal).toBe(1);
      expect(start('%4').ordinal).toBe(2);
    });
  });

  it('облик проекта из avatars.json — у агентов этого хозяина, не у агентов другого хозяина с тем же проектом', () => {
    const r = new EntityRegistry(office.bundle.config.people, chars, { people: new Map(), projects: new Map([['agent:p1:demo', LOOK]]) });
    expect(r.ensureAgent('p1', { project: 'demo', slot: '%1' }, T0, noneActive).entity.avatar).toEqual(LOOK);
    expect(r.ensureAgent('p2', { project: 'demo', slot: '%1' }, T0, noneActive).entity.avatar).toEqual(defaultProjectAvatar('p2', 'demo', chars.pool));
    expect(r.projectAvatar('p1', 'demo')).toEqual(LOOK);
  });

  it('setProjectAvatar переодевает всех агентов проекта с учётом номера; hasAgents', () => {
    const r = reg();
    const live = new Set<string>();
    const active = (id: string) => live.has(id);
    const a = r.ensureAgent('p1', { project: 'demo', slot: '%1' }, T0, active).entity;
    live.add(a.id);
    const b = r.ensureAgent('p1', { project: 'demo', slot: '%2' }, T0, active).entity;
    const other = r.ensureAgent('p1', { project: 'api', slot: '%3' }, T0, active).entity;
    const otherBefore = other.avatar;
    expect(r.setProjectAvatar('p1', 'demo', LOOK, active).map((x) => x.id)).toEqual([a.id, b.id]);
    expect(a.avatar).toEqual(LOOK);
    expect(b.avatar).toEqual({ ...LOOK, outfit: [5, 3] }); // у модели одежды 5 пять цветов: второй — цвет 2 + 1
    expect(other.avatar).toEqual(otherBefore);
    expect([r.hasAgents('p1', 'demo'), r.hasAgents('p2', 'demo'), r.hasAgents('p1', 'nope')]).toEqual([true, false, false]);
  });

  it('restore: агент из снимка без номера — номер 1; облик и подпись пересчитаны по проекту', () => {
    const r = reg();
    r.restore([{ id: 'agent:p1:demo:%1', kind: 'agent', name: 'Старое · demo', ownerId: 'p1', project: 'demo', slot: '%1', avatar: avatarFromKey('agent:p1:demo:%1', chars.pool), lastEventAt: T0 }]);
    const a = r.agent('agent:p1:demo:%1')!;
    expect([a.ordinal, a.name]).toEqual([1, 'Стас · demo']);
    expect(a.avatar).toEqual(defaultProjectAvatar('p1', 'demo', chars.pool));
  });

  it('settleRestored: повторы номеров активных агентов снимаются по lastEventAt, затем id; агенты в offline не трогаются', () => {
    const r = reg();
    const stored = (slot: string, lastEventAt: number, ordinal?: number) => ({
      id: `agent:p1:demo:${slot}`, kind: 'agent' as const, name: 'x', ownerId: 'p1', project: 'demo', slot, avatar: LOOK, lastEventAt, ...(ordinal ? { ordinal } : {}),
    });
    r.restore([stored('%3', T0 + 10), stored('%4', T0), stored('%5', T0), stored('%6', T0, 1)]);
    r.settleRestored((id) => id !== 'agent:p1:demo:%6');
    const ord = (slot: string) => r.agent(`agent:p1:demo:${slot}`)!.ordinal;
    expect([ord('%4'), ord('%5'), ord('%3'), ord('%6')]).toEqual([1, 2, 3, 1]);
    expect(r.agent('agent:p1:demo:%5')!.name).toBe('Стас · demo 2');
  });

  it('settleRestored: одинаковые номера у разных хозяев и проектов — не повтор, не разводятся', () => {
    const r = reg();
    const stored = (owner: string, project: string, slot: string) => ({
      id: `agent:${owner}:${project}:${slot}`, kind: 'agent' as const, name: 'x', ownerId: owner, project, slot, avatar: LOOK, lastEventAt: T0, ordinal: 1,
    });
    r.restore([stored('p1', 'demo', '%1'), stored('p1', 'api', '%2'), stored('p2', 'demo', '%3'), stored('p1', 'demo', '%4')]);
    r.settleRestored(() => true);
    expect(r.agentList().map((a) => [a.id, a.ordinal])).toEqual([
      ['agent:p1:demo:%1', 1],
      ['agent:p1:api:%2', 1],
      ['agent:p2:demo:%3', 1],
      ['agent:p1:demo:%4', 2],
    ]);
  });

  it('renumber неизвестного id — false', () => {
    expect(reg().renumber('agent:p1:demo:%1', () => true)).toBe(false);
  });

  describe('метка агента в подписи (спека метки §4.2)', () => {
    const L = (text: string) => ({ text, private: false });
    const setup = () => {
      const r = reg();
      const live = new Set<string>();
      const active = (id: string) => live.has(id);
      // Как runtime: статус принят → номер → метка → пересчёт подписей пары.
      const start = (slot: string, label?: { text: string; private: boolean }) => {
        const { entity } = r.ensureAgent('p1', { project: 'pixeloffice', slot }, T0, active);
        live.add(entity.id);
        r.renumber(entity.id, active);
        if (label) r.setLabel(entity.id, label);
        r.relabel('p1', 'pixeloffice', active);
        return entity;
      };
      return { r, live, active, start };
    };

    it('метка есть — «хозяин · проект · метка», номер не пишется', () => {
      const { r, start } = setup();
      start('%1');
      const b = start('%2', L('tmux names'));
      expect([b.ordinal, b.name]).toEqual([2, 'Стас · pixeloffice · tmux names']);
      expect(r.caption(b)).toEqual({ head: 'Стас · pixeloffice · tmux names', ordinal: 1 });
    });

    it('совпадение меток у активных агентов проекта — у второго номер, у первого (номер 1) — нет', () => {
      const { r, start } = setup();
      const a = start('%1', L('street'));
      const b = start('%2', L('street'));
      expect([a.name, b.name]).toEqual(['Стас · pixeloffice · street', 'Стас · pixeloffice · street 2']);
      expect(r.caption(b)).toEqual({ head: 'Стас · pixeloffice · street', ordinal: 2 });
    });

    it('relabel возвращает только изменившихся; агент в offline в совпадении не считается и не пересчитывается', () => {
      const { r, live, active, start } = setup();
      const a = start('%1', L('street'));
      const b = start('%2', L('street'));
      r.setLabel(b.id, L('door'));
      expect(r.relabel('p1', 'pixeloffice', active).map((x) => x.id)).toEqual([b.id]);
      expect([a.name, b.name]).toEqual(['Стас · pixeloffice · street', 'Стас · pixeloffice · door']);
      r.setLabel(b.id, L('street'));
      expect(r.relabel('p1', 'pixeloffice', active).map((x) => x.id)).toEqual([b.id]);
      expect(b.name).toBe('Стас · pixeloffice · street 2');
      live.delete(b.id); // b ушёл в offline: у a совпадения нет, подпись b не меняется
      expect(r.relabel('p1', 'pixeloffice', active)).toEqual([]);
      expect(b.name).toBe('Стас · pixeloffice · street 2');
      live.add(b.id);
      live.delete(a.id); // a ушёл: у b пропадает номер
      expect(r.relabel('p1', 'pixeloffice', active).map((x) => x.id)).toEqual([b.id]);
      expect(b.name).toBe('Стас · pixeloffice · street');
    });

    it('relabel сравнивает части подписи, а не name: «x 2» без номера → «x» с номером 2', () => {
      const { r, active, start } = setup();
      start('%1', L('x'));
      const b = start('%2', L('x 2'));
      expect(b.name).toBe('Стас · pixeloffice · x 2');
      r.setLabel(b.id, L('x'));
      // name тот же, но усечённая подпись другая: номер теперь сохраняется при усечении (риск 4 преамбулы)
      expect(r.relabel('p1', 'pixeloffice', active).map((x) => x.id)).toEqual([b.id]);
      expect([b.name, r.caption(b)]).toEqual(['Стас · pixeloffice · x 2', { head: 'Стас · pixeloffice · x', ordinal: 2 }]);
    });

    it('setProjectAvatar: агент в offline получает облик проекта, подпись не пересчитывается (спека метки §4.3)', () => {
      const { r, live, active, start } = setup();
      const a = start('%1', L('street'));
      const b = start('%2', L('street'));
      live.delete(b.id); // b ушёл в offline с подписью «… · street 2»
      r.setLabel(a.id, L('door'));
      r.relabel('p1', 'pixeloffice', active);
      r.setProjectAvatar('p1', 'pixeloffice', LOOK, active);
      expect(b.avatar).toEqual({ ...LOOK, outfit: [5, 3] }); // облик — с учётом номера 2
      expect([b.name, r.caption(b)]).toEqual(['Стас · pixeloffice · street 2', { head: 'Стас · pixeloffice · street', ordinal: 2 }]);
      expect(a.name).toBe('Стас · pixeloffice · door');
    });

    it('setLabel(null) удаляет поле — подпись снова с номером', () => {
      const { r, active, start } = setup();
      start('%1');
      const b = start('%2', L('x'));
      r.setLabel(b.id, null);
      r.relabel('p1', 'pixeloffice', active);
      expect('label' in b).toBe(false);
      expect(b.name).toBe('Стас · pixeloffice 2');
      expect(r.caption(b)).toEqual({ head: 'Стас · pixeloffice', ordinal: 2 });
    });

    it('restore + settleRestored: метка из снимка — в подписи, совпадение у активных — номер', () => {
      const r = reg();
      const base = { kind: 'agent' as const, name: 'старое', ownerId: 'p1', project: 'demo', avatar: avatarFromKey('x', chars.pool), lastEventAt: T0 };
      r.restore([
        { ...base, id: 'agent:p1:demo:%1', slot: '%1', ordinal: 1, label: L('street') },
        { ...base, id: 'agent:p1:demo:%2', slot: '%2', ordinal: 2, label: L('street') },
      ]);
      r.settleRestored(() => true);
      expect(r.agentList().map((a) => a.name)).toEqual(['Стас · demo · street', 'Стас · demo · street 2']);
    });
  });
});
