import { mkdirSync, mkdtempSync, renameSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { describe, expect, it } from 'vitest';
import { expandHome, validateOfficesDir } from '../src/index.ts';
import { MINI_CATALOG, MINI_CONFIG, MINI_PEOPLE, MINI_RULES, ROUTES_OFFICE, SIGN_CATALOG, SITE_CATALOG, UI_CATALOG, WORLD_OFFICE, mutateYaml } from '../../../packages/core/tests/fixtures.ts';
import { fakeAssets, realPng } from './png.ts';

function makeRoot(officeText: string, configText = mutateYaml(MINI_CONFIG, (d) => (d.catalog = '../../catalog.yaml')), catalogText = MINI_CATALOG, peopleText = MINI_PEOPLE) {
  const root = mkdtempSync(join(tmpdir(), 'po-maps-'));
  writeFileSync(join(root, 'catalog.yaml'), catalogText);
  const dir = join(root, 'offices', 'test');
  mkdirSync(dir, { recursive: true });
  writeFileSync(join(dir, 'office.yaml'), officeText);
  writeFileSync(join(dir, 'rules.yaml'), MINI_RULES);
  writeFileSync(join(dir, 'config.example.yaml'), configText);
  writeFileSync(join(dir, 'people.yaml'), peopleText);
  return join(root, 'offices');
}

describe('validateOfficesDir', () => {
  it('валидный офис — без ошибок (config.example.yaml как запасной)', async () => {
    const [rep] = await validateOfficesDir(makeRoot(WORLD_OFFICE));
    expect(rep!.errors).toEqual([]);
  });

  it('ошибки карты попадают в отчёт с кодом и координатами', async () => {
    const [rep] = await validateOfficesDir(makeRoot(WORLD_OFFICE.replace('#^^^^.^^..^^.#', '#^^^^.^^..^^#')));
    expect(rep!.errors.join('\n')).toContain('grid_ragged');
  });

  it('предупреждения карты — в отчёте, не ошибки', async () => {
    const config = mutateYaml(MINI_CONFIG, (d) => (d.catalog = '../../catalog.yaml'));
    const people = mutateYaml(MINI_PEOPLE, (d) => {
      d.people[0].commute = 'car';
      d.people.push({ id: 'b', name: 'Борис', pod: 'pod:b', commute: 'car' });
    });
    // Место парковки становится просто тротуаром: человеку на машине некуда приехать.
    const office = mutateYaml(ROUTES_OFFICE, (d) => {
      d.site.legend.c = 'sidewalk';
      // Угол второго человека на машине: предупреждений два.
      d.zones.push({ id: 'pod:b', kind: 'pod', rect: [10, 11, 2, 2] });
      d.placements.push({ item: 'chair', at: [10, 11], facing: 'down', tags: ['owner_seat'] });
    });
    const [rep] = await validateOfficesDir(makeRoot(office, config, SITE_CATALOG, people));
    expect(rep!.errors).toEqual([]);
    // По строке на предупреждение: cli ставит пометку «предупреждение» перед каждой (решение 21 плана).
    expect(rep!.warnings).toHaveLength(2);
    for (const w of rep!.warnings) expect(w).toMatch(/^[^\n]*\[commute_fallback\][^\n]*$/);
  });

  it('листов интерфейса нет — заметка, а не ошибка (спека интерфейса §3.2)', async () => {
    const assets = fakeAssets(128, 160);
    const config = mutateYaml(MINI_CONFIG, (d) => {
      d.catalog = '../../catalog.yaml';
      d.assetsDir = assets;
    });
    const [rep] = await validateOfficesDir(makeRoot(WORLD_OFFICE, config, UI_CATALOG));
    expect(rep!.errors).toEqual([]);
    expect(rep!.notes).toContain('интерфейс: нет листов test/ui-cold.png, test/ui-warm.png');
  });

  it('нет каталога offices — пустой отчёт', async () => {
    expect(await validateOfficesDir('/nonexistent/offices')).toEqual([]);
  });

  it('expandHome раскрывает ~', () => {
    expect(expandHome('~/tmp')).not.toContain('~');
    expect(expandHome('/abs')).toBe('/abs');
  });

  it('people.example.yaml — запасной при config.example.yaml, people.yaml важнее (план хостинга, отступление 1)', async () => {
    const root = makeRoot(WORLD_OFFICE);
    const dir = join(root, 'test');
    renameSync(join(dir, 'people.yaml'), join(dir, 'people.example.yaml'));
    expect((await validateOfficesDir(root))[0]!.errors).toEqual([]);
    writeFileSync(join(dir, 'people.yaml'), 'people: []\n'); // owner a исчез — owner_unknown: читается people.yaml
    expect((await validateOfficesDir(root))[0]!.errors.join('\n')).toContain('owner_unknown');
  });
});

describe('validateOfficesDir: вывеска (спека вывески 6.1 п. 6)', () => {
  const signRoot = (sign: Record<string, unknown>) =>
    makeRoot(
      ROUTES_OFFICE,
      mutateYaml(MINI_CONFIG, (d) => {
        d.catalog = '../../catalog.yaml';
        d.sign = sign;
      }),
      SIGN_CATALOG,
    );

  it('логотип на месте и надпись влезает — без ошибок', async () => {
    const root = signRoot({ text: 'Hi', logo: 'logo.png' });
    writeFileSync(join(root, 'test', 'logo.png'), realPng(10, 10));
    const [rep] = await validateOfficesDir(root);
    expect(rep!.errors).toEqual([]);
  });

  it('опечатка в пути логотипа — sign_logo с путём, в файле конфига', async () => {
    const root = signRoot({ text: 'Hi', logo: 'logo.png' });
    const [rep] = await validateOfficesDir(root);
    const e = rep!.errors.join('\n');
    expect(e).toContain('config.example.yaml: [sign_logo]');
    expect(e).toContain(`нет файла ${join(root, 'test', 'logo.png')}`);
  });

  it('слишком длинная надпись — sign_too_wide в файле конфига', async () => {
    const [rep] = await validateOfficesDir(signRoot({ text: 'X'.repeat(24) }));
    expect(rep!.errors.join('\n')).toMatch(/config\.example\.yaml: \[sign_too_wide\] sign: вывеска 198 px/);
  });
});
