import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterAll, describe, expect, it } from 'vitest';
import type { AvatarParts, HelloMessage } from '@pixeloffice/protocol';
import { avatarLayerPaths, defaultAssetUrl, defaultProjectAvatar } from '@pixeloffice/core/characters';
import { AvatarStore, ManualClock, OfficeRuntime, memoryLogger, officeAvatars } from '../src/index.ts';
import { demoOffice } from './helpers.ts';

const office = demoOffice();
const pool = office.bundle.catalog.characters.pool;
const IDS = office.bundle.config.people.map((p) => p.id);
const LOOK: AvatarParts = { body: 2, eyes: 3, outfit: [5, 2], hair: [7, 3], accessory: [15, 1] };
const dirs: string[] = [];
const tmp = () => {
  const d = mkdtempSync(join(tmpdir(), 'po-avatars-'));
  dirs.push(d);
  return d;
};
afterAll(() => {
  for (const d of dirs) rmSync(d, { recursive: true, force: true });
});
const fileOf = (dir: string) => JSON.parse(readFileSync(join(dir, 'avatars.json'), 'utf8')) as unknown;
const NONE = { people: new Map(), projects: new Map() };

describe('AvatarStore', () => {
  it('нет файла — переопределений нет', () => {
    expect(new AvatarStore(tmp(), memoryLogger()).effective(IDS, pool)).toEqual(NONE);
  });

  it('сохранение атомарно и переживает перезапуск', () => {
    const dir = tmp();
    new AvatarStore(dir, memoryLogger()).save('p1', LOOK);
    expect(fileOf(dir)).toEqual({ p1: LOOK });
    expect(existsSync(join(dir, 'avatars.json.tmp'))).toBe(false);
    expect(new AvatarStore(dir, memoryLogger()).effective(IDS, pool)).toEqual({ people: new Map([['p1', LOOK]]), projects: new Map() });
  });

  it('битый файл (не JSON или не объект) — предупреждение, файл отложен в avatars.json.bad-<время>, обликов нет', () => {
    for (const text of ['{обрыв', '[1, 2]', '"строка"', 'null']) {
      const dir = tmp();
      writeFileSync(join(dir, 'avatars.json'), text);
      const log = memoryLogger();
      const s = new AvatarStore(dir, log, () => new Date('2026-10-21T10:00:00.000Z'));
      expect(s.effective(IDS, pool)).toEqual(NONE);
      expect(readdirSync(dir)).toEqual(['avatars.json.bad-2026-10-21T10-00-00-000Z']);
      expect(readFileSync(join(dir, 'avatars.json.bad-2026-10-21T10-00-00-000Z'), 'utf8')).toBe(text);
      expect(log.lines.some((l) => l.level === 'warn' && l.msg.includes('avatars.json'))).toBe(true);
    }
  });

  it('файл не прочитать — предупреждение, файл не отложен, обликов нет, запись отключена', () => {
    const dir = tmp();
    mkdirSync(join(dir, 'avatars.json')); // на месте файла каталог — readFileSync: EISDIR
    const log = memoryLogger();
    const s = new AvatarStore(dir, log);
    expect(s.effective(IDS, pool)).toEqual(NONE);
    expect(readdirSync(dir)).toEqual(['avatars.json']);
    expect(log.lines.some((l) => l.level === 'warn' && l.msg.includes('не прочитан'))).toBe(true);
    expect(() => s.save('p1', LOOK)).toThrow();
  });

  it('запись про неизвестного человека и облик вне каталога не действуют, но не пропадают при сохранении', () => {
    const dir = tmp();
    const ghost = { body: 1, eyes: 1, outfit: [1, 1], hair: [1, 1] };
    const broken = { ...LOOK, outfit: [41, 2] };
    const zero = { ...ghost, body: 0 };
    writeFileSync(join(dir, 'avatars.json'), JSON.stringify({ ghost, p2: broken, p3: 'мусор', p4: zero }));
    const log = memoryLogger();
    const s = new AvatarStore(dir, log);
    expect(s.effective(IDS, pool)).toEqual(NONE);
    const warns = log.lines.filter((l) => l.level === 'warn').map((l) => l.msg);
    expect(warns.slice(0, 2)).toEqual([
      'avatars.json: человека «ghost» нет в конфиге — запись не действует',
      'avatars.json: облик «p2» не действует (одежда: модели 41 нет в каталоге)',
    ]);
    // Ошибка схемы называет поле — как в ответе PUT (parseAvatarParts), а не общее «не по схеме».
    expect(warns[2]).toMatch(/^avatars\.json: облик «p3» не действует \(<корень>: .+\)$/);
    expect(warns[3]).toMatch(/^avatars\.json: облик «p4» не действует \(body: .+\)$/);
    expect(warns).toHaveLength(4);
    s.save('p1', LOOK);
    expect(fileOf(dir)).toEqual({ ghost, p2: broken, p3: 'мусор', p4: zero, p1: LOOK });
  });

  it('ошибка записи — исключение, записи в памяти прежние', () => {
    const dir = tmp();
    const s = new AvatarStore(dir, memoryLogger());
    mkdirSync(join(dir, 'avatars.json.tmp')); // запись временного файла в каталог — EISDIR
    expect(() => s.save('p1', LOOK)).toThrow();
    rmSync(join(dir, 'avatars.json.tmp'), { recursive: true });
    s.save('p2', LOOK);
    expect(fileOf(dir)).toEqual({ p2: LOOK });
  });

  it('сбой rename — исключение, временный файл не остаётся', () => {
    const dir = tmp();
    const s = new AvatarStore(dir, memoryLogger());
    mkdirSync(join(dir, 'avatars.json')); // каталог на месте файла появился после старта: rename файла поверх — EISDIR
    writeFileSync(join(dir, 'avatars.json', 'x'), '');
    expect(() => s.save('p1', LOOK)).toThrow();
    expect(readdirSync(dir)).toEqual(['avatars.json']);
  });

  it('облик проекта agent:<хозяин>:<проект> — отдельно от людей; неизвестный хозяин не действует, но запись сохраняется', () => {
    const dir = tmp();
    const ghostProject = { body: 1, eyes: 1, outfit: [1, 1], hair: [1, 1] };
    const broken = { ...LOOK, outfit: [41, 2] };
    writeFileSync(join(dir, 'avatars.json'), JSON.stringify({ 'agent:p1:org/repo:main': LOOK, 'agent:ghost:demo': ghostProject, 'agent:p2:x': broken }));
    const log = memoryLogger();
    const s = new AvatarStore(dir, log);
    expect(s.effective(IDS, pool)).toEqual({ people: new Map(), projects: new Map([['agent:p1:org/repo:main', LOOK]]) });
    expect(log.lines.filter((l) => l.level === 'warn').map((l) => l.msg)).toEqual([
      'avatars.json: хозяина «ghost» нет в конфиге — облик проекта «agent:ghost:demo» не действует',
      'avatars.json: облик «agent:p2:x» не действует (одежда: модели 41 нет в каталоге)',
    ]);
    s.save('p1', LOOK);
    expect(fileOf(dir)).toEqual({ 'agent:p1:org/repo:main': LOOK, 'agent:ghost:demo': ghostProject, 'agent:p2:x': broken, p1: LOOK });
  });
});

describe('облики для serve', () => {
  it('тестовый режим: avatars.json не читается и не пишется — хранилища нет, облики из конфига (§3.1.4)', () => {
    const dir = tmp();
    writeFileSync(join(dir, 'avatars.json'), JSON.stringify({ p1: LOOK }));
    expect(officeAvatars(dir, IDS, pool, true, memoryLogger())).toEqual({ store: null, effective: undefined });
    expect(fileOf(dir)).toEqual({ p1: LOOK });
    const live = officeAvatars(dir, IDS, pool, false, memoryLogger());
    expect(live.store).toBeInstanceOf(AvatarStore);
    expect(live.effective).toEqual({ people: new Map([['p1', LOOK]]), projects: new Map() });
  });
});

describe('облики в runtime и hello', () => {
  const runtime = (dir?: string) =>
    new OfficeRuntime({ office, clock: new ManualClock(), log: memoryLogger(), avatars: dir ? new AvatarStore(dir, memoryLogger()).effective(IDS, pool) : undefined });
  const human = (h: HelloMessage, id: string) => h.entities.find((e) => e.id === id)!;
  const configAvatar = (id: string) => office.bundle.config.people.find((p) => p.id === id)!.avatar;

  it('hello: avatarKit из каталога; у людей avatar; у агента — облик проекта и project; URL из avatarKit совпадают с layers', () => {
    const rt = runtime();
    rt.ingestFromSource(rt.sourceByName('claude-hook')!, [{ type: 'status', agent: { project: 'P', slot: '%1' }, status: 'working', at: new Date().toISOString() }]);
    const h = JSON.parse(JSON.stringify(rt.hello())) as HelloMessage; // как его видит вьюер — после JSON
    const c = office.bundle.catalog.characters;
    expect(h.avatarKit).toEqual({ pool: c.pool, accessoryNames: c.accessoryNames, layers: c.layers });
    const humans = h.entities.filter((e) => e.kind === 'human');
    expect(humans).toHaveLength(9);
    for (const e of humans) {
      expect(e.avatar).toEqual(configAvatar(e.id));
      expect(avatarLayerPaths(h.avatarKit, e.avatar!).map(defaultAssetUrl)).toEqual(e.layers);
    }
    const agent = h.entities.find((e) => e.kind === 'agent')!;
    expect(agent.project).toBe('P');
    expect(agent.avatar).toEqual(defaultProjectAvatar('p1', 'P', c.pool));
  });

  it('перезапуск: облик из avatars.json важнее облика из конфига', () => {
    const dir = tmp();
    new AvatarStore(dir, memoryLogger()).save('p1', LOOK);
    const p1 = human(runtime(dir).hello(), 'p1');
    expect(p1.avatar).toEqual(LOOK);
    expect(p1.layers).toEqual(avatarLayerPaths(office.bundle.catalog.characters, LOOK).map(defaultAssetUrl));
    expect(human(runtime(dir).hello(), 'p2').avatar).toEqual(configAvatar('p2'));
  });

  it('битый avatars.json: runtime стартует, облики из конфига', () => {
    const dir = tmp();
    writeFileSync(join(dir, 'avatars.json'), '{обрыв');
    expect(human(runtime(dir).hello(), 'p1').avatar).toEqual(configAvatar('p1'));
  });

  it('setAvatar: человек — новый EntityView со слоями и avatar; агент и неизвестный — null', () => {
    const rt = runtime();
    const view = rt.setAvatar('p1', LOOK)!;
    expect(view.avatar).toEqual(LOOK);
    expect(view.layers).toEqual(avatarLayerPaths(office.bundle.catalog.characters, LOOK).map(defaultAssetUrl));
    expect(human(rt.hello(), 'p1').avatar).toEqual(LOOK);
    rt.ingestFromSource(rt.sourceByName('claude-hook')!, [{ type: 'status', agent: { project: 'P', slot: '%1' }, status: 'working', at: new Date().toISOString() }]);
    expect(rt.setAvatar('agent:p1:P:%1', LOOK)).toBeNull();
    expect(rt.setAvatar('nobody', LOOK)).toBeNull();
  });

  it('облик проекта сохранён до drain: entity нового агента в очереди уходит уже с новым обликом', () => {
    const rt = runtime();
    rt.ingestFromSource(rt.sourceByName('claude-hook')!, [{ type: 'status', agent: { project: 'P', slot: '%1' }, status: 'working', at: new Date().toISOString() }]);
    expect(rt.setProjectAvatar('p1', 'P', LOOK).map((v) => v.avatar)).toEqual([LOOK]); // рассылка мимо очереди
    const queued = rt.drain().flatMap((m) => (m.type === 'entity' ? [m.entity] : []));
    expect(queued.map((v) => [v.id, v.avatar])).toEqual([['agent:p1:P:%1', LOOK]]);
    expect(queued[0]!.layers).toEqual(avatarLayerPaths(office.bundle.catalog.characters, LOOK).map(defaultAssetUrl));
  });
});
