import { cpSync, existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { stringify } from 'yaml';
import { LIMITS, checkFileSet, filesToWire, mergeFiles, parseAdminBody, readOfficeFileSet, writeOfficeFileSet } from '../src/index.ts';
import { realPng } from '../../../tools/validate-maps/tests/png.ts';
import { DEMO_DIR, demoOffice } from './helpers.ts';

const demo = demoOffice;
const base = () => ({ config: demo().texts.config, catalog: demo().texts.catalog });
const codes = (r: { errors: { code: string }[] }) => r.errors.map((e) => e.code);

describe('parseAdminBody (спека хостинга 5.2, 5.3)', () => {
  it('частичный набор, комментарий, baseVersion; логотип base64 → Buffer, null — удалить', () => {
    const r = parseAdminBody({ files: { 'rules.yaml': 'x', 'logo.png': Buffer.from([1, 2]).toString('base64') }, comment: 'c', baseVersion: 3 });
    expect(r).toEqual({ ok: true, value: { files: { 'rules.yaml': 'x', 'logo.png': Buffer.from([1, 2]) }, comment: 'c', baseVersion: 3 } });
    expect(parseAdminBody({ files: { 'logo.png': null } })).toEqual({ ok: true, value: { files: { 'logo.png': null } } });
    expect(parseAdminBody({})).toEqual({ ok: true, value: { files: {} } });
  });
  it('неизвестный ключ, логотип не base64, не объект — ошибка формы', () => {
    for (const b of [{ files: { 'config.yaml': 'x' } }, { files: { 'logo.png': 'не base64!' } }, { files: {}, extra: 1 }, 'текст', null])
      expect(parseAdminBody(b).ok, JSON.stringify(b)).toBe(false);
  });
});

describe('набор файлов на диске', () => {
  it('чтение: нет people.yaml — пустой список; запись атомарная, логотип null удаляет файл', () => {
    const dir = mkdtempSync(join(tmpdir(), 'po-files-'));
    cpSync(DEMO_DIR, dir, { recursive: true });
    const files = { ...demo().files, dir, officePath: join(dir, 'office.yaml'), rulesPath: join(dir, 'rules.yaml'), peoplePath: join(dir, 'people.yaml'), configPath: join(dir, 'config.yaml') };
    const set = readOfficeFileSet(files);
    expect(set['logo.png']).not.toBeNull();
    writeOfficeFileSet(files, { ...set, 'rules.yaml': set['rules.yaml'] + '# правка\n', 'logo.png': null });
    expect(readFileSync(join(dir, 'rules.yaml'), 'utf8')).toContain('# правка');
    expect(existsSync(join(dir, 'logo.png'))).toBe(false);
    expect(filesToWire(readOfficeFileSet(files))['logo.png']).toBeNull();
    rmSync(files.peoplePath); // копия demo несёт people.yaml — ветку «нет файла» проверяем, удалив его
    expect(readOfficeFileSet(files)['people.yaml']).toBe('people: []\n');
  });
});

describe('checkFileSet (спека хостинга 4.2 п. 2, 5.4, 5.5)', () => {
  const current = () => readOfficeFileSet(demo().files);
  it('годный набор — ok, бандл собран', () => {
    const r = checkFileSet(current(), base());
    expect(r.errors).toEqual([]);
    expect(r.ok && r.bundle.config.people.length).toBe(9);
  });
  it('ошибка карты — ok: false, поле at переименовано в cell', () => {
    const set = mergeFiles(current(), { 'office.yaml': current()['office.yaml'].replace('placements:', 'placements:\n  - { item: chair, at: [16, 21], facing: up }') });
    const r = checkFileSet(set, base());
    expect(r.ok).toBe(false);
    const withCell = r.errors.find((e) => e.cell);
    expect(withCell).toBeDefined();
    expect('at' in withCell!).toBe(false);
  });
  it('логотип из набора: не PNG — sign_logo; sign.logo без logo.png — «нет файла»', () => {
    expect(codes(checkFileSet({ ...current(), 'logo.png': Buffer.from('не png') }, base()))).toContain('sign_logo');
    const none = checkFileSet({ ...current(), 'logo.png': null }, base());
    expect(none.errors.map((e) => e.message).join('\n')).toContain('нет файла logo.png');
    expect(checkFileSet({ ...current(), 'logo.png': realPng(10, 10) }, base()).ok).toBe(true);
  });
  it('лимиты: комментарий, люди, сетка — limit_exceeded', () => {
    expect(codes(checkFileSet(current(), base(), 'x'.repeat(LIMITS.comment + 1)))).toContain('limit_exceeded');
    const many = stringify({ people: Array.from({ length: LIMITS.people + 1 }, (_, i) => ({ id: `u${i}`, name: `U${i}`, pod: 'pod:p1' })) });
    expect(codes(checkFileSet({ ...current(), 'people.yaml': many }, base()))).toContain('limit_exceeded');
  });
  it('сетка карты ходьбы больше 150×100 — limit_exceeded', () => {
    const office = (w: number) =>
      stringify({
        floor: { default: 'carpet_grey' },
        legend: { '#': 'wall', '.': 'floor', E: 'entrance' },
        grid: ['#'.repeat(w), '#' + '.'.repeat(w - 2) + '#', '#'.repeat(70) + '.E.' + '#'.repeat(w - 73)].join('\n') + '\n',
      });
    const rules = 'dwell: { agent: 20s, human: 60s }\nhuman: { online: [exit], meeting: [exit], offline: [exit] }\nagent: { working: [exit], idle: [exit], needs_input: [exit], offline: [exit] }\n';
    const cfg = 'officeId: t\nassetsDir: x\ndataDir: y\nviewerTokens: [viewer-token-1]\n';
    const set = (w: number) => ({ 'office.yaml': office(w), 'rules.yaml': rules, 'people.yaml': 'people: []\n', 'logo.png': null });
    const b = { config: cfg, catalog: base().catalog };
    expect(checkFileSet(set(150), b).errors).toEqual([]);
    expect(codes(checkFileSet(set(151), b))).toEqual(['limit_exceeded']);
  });
  it('сетка больше лимита — limit_exceeded до сборки, даже при других ошибках набора', () => {
    // Сетка 1000×1000 с битой легендой: сборка дала бы ошибки легенды, а лимит не попал бы в ответ. Единственная
    // ошибка — лимит, значит, сборки не было; замер времени здесь не нужен, под нагрузкой он флейкает.
    const grid = Array.from({ length: 1000 }, () => '?'.repeat(1000)).join('\n') + '\n';
    const set = { ...current(), 'office.yaml': stringify({ floor: { default: 'carpet_grey' }, legend: { '#': 'wall' }, grid }) };
    const r = checkFileSet(set, base());
    expect(r.errors).toEqual([{ file: 'office.yaml', code: 'limit_exceeded', message: 'сетка здания grid 1000×1000 клеток, можно не больше 150×100' }]);
    const site = mergeFiles(current(), { 'office.yaml': current()['office.yaml'].replace(/(site:\n(?:.*\n)*?  grid: \|\n)/, `$1${'    ' + ','.repeat(200) + '\n'}`) });
    expect(checkFileSet(site, base()).errors.map((e) => e.message)).toContain('сетка участка site.grid 200×42 клеток, можно не больше 150×100');
  });
});
