import { describe, expect, it } from 'vitest';
import { buildWorldMap, loadOfficeBundle, parsePeople, reachableFrom, validateWorld } from '../src/index.ts';
import { MINI_CONFIG, MINI_PEOPLE, MINI_RULES, ROUTES_OFFICE, SITE_CATALOG, WORLD_OFFICE, asciiMap, miniCatalog, mutateYaml, office, tinyOffice } from './fixtures.ts';

const people = (fn?: (d: any) => void) => {
  const r = parsePeople(fn ? mutateYaml(MINI_PEOPLE, fn) : MINI_PEOPLE);
  if (!r.ok) throw new Error(JSON.stringify(r.errors));
  return r.value;
};
const noPeople = (d: any) => {
  d.people = [];
};
const errorsOf = (officeText: string, list = people()) => {
  const m = buildWorldMap(office(officeText), miniCatalog());
  if (!m.ok) throw new Error(JSON.stringify(m.errors));
  return validateWorld(m.value, list);
};

describe('validateWorld', () => {
  it('тестовый офис валиден', () => {
    expect(errorsOf(WORLD_OFFICE)).toEqual([]);
  });

  it('регрессия v1: вход в стене (за входом стол)', () => {
    const text = mutateYaml(WORLD_OFFICE, (d) => (d.grid = d.grid.replace('#p.p.........#\n######E', '#p.p..DD.....#\n######E')));
    expect(errorsOf(text).map((e) => e.code)).toContain('entrance_enclosed');
  });

  it('регрессия v1 (d9): карман — кресло окружено фикусами', () => {
    const text = tinyOffice(['#######', '#^f...#', '#f....#', '#.....#', '###E###'], { '^': { item: 'chair', facing: 'up' }, f: 'plant' });
    const e = errorsOf(text, people(noPeople));
    expect(e).toEqual([expect.objectContaining({ code: 'spot_unreachable', at: [1, 1] })]);
  });

  it('регрессия v1 (d4): места не транзит — среднее кресло в ряду у стены недостижимо', () => {
    const text = tinyOffice(['######', '#vvv.#', '#DD..#', '#....#', '##E###'], { v: { item: 'chair', facing: 'down' }, D: 'desk' });
    const at = errorsOf(text, people(noPeople)).filter((e) => e.code === 'spot_unreachable').map((e) => e.at);
    expect(at).toEqual([[1, 1], [2, 1]]);
  });

  it('на клетке входа место (кресло) — одна ошибка entrance_blocked вместо потока spot_unreachable', () => {
    const text = mutateYaml(WORLD_OFFICE, (d) => d.placements.push({ item: 'chair', facing: 'up', at: [6, 6] }));
    expect(errorsOf(text).map((e) => e.code)).toEqual(['entrance_blocked']);
  });

  it('нет входа', () => {
    const text = mutateYaml(WORLD_OFFICE, (d) => (d.grid = d.grid.replace('E', '#')));
    expect(errorsOf(text).map((e) => e.code)).toContain('entrance_missing');
  });

  it('угол человека: нет зоны, не pod, общий угол, углов меньше людей', () => {
    expect(errorsOf(WORLD_OFFICE, people((d) => (d.people[0].pod = 'pod:zzz'))).map((e) => e.code)).toContain('person_pod_missing');
    expect(errorsOf(WORLD_OFFICE, people((d) => (d.people[0].pod = 'lounge'))).map((e) => e.code)).toContain('person_pod_kind');
    const two = people((d) => d.people.push({ ...d.people[0], id: 'b' }));
    expect(errorsOf(WORLD_OFFICE, two).map((e) => e.code).sort()).toEqual(['pod_shared', 'pods_too_few']);
  });

  it('в углу ровно один owner_seat', () => {
    const text = mutateYaml(WORLD_OFFICE, (d) => (d.placements = d.placements.filter((p: any) => !p.tags)));
    expect(errorsOf(text).map((e) => e.code)).toContain('owner_seat_count');
  });

  it('достижимость — по индексам карты со сдвигом (спека маршрутов 4.1)', () => {
    const m = asciiMap(['..#S', '..#.', 'E.#.'], [-2, -1]);
    const seen = reachableFrom(m, [-2, 1]);
    expect(seen[m.index(-1, -1)]).toBe(1);
    expect(seen[m.index(1, 0)]).toBe(0);
    expect(validateWorld(m, []).map((e) => [e.code, e.at])).toEqual([['spot_unreachable', [1, -1]]]);
  });

  it('site_unreachable: портал недостижим от входа (спека маршрутов 3.8)', () => {
    const noZebra = mutateYaml(ROUTES_OFFICE, (d) => (d.site.grid = d.site.grid.replaceAll('==zz==', '======').replaceAll('::zz::', '::::::')));
    const r = loadOfficeBundle({ office: noZebra, rules: MINI_RULES, config: MINI_CONFIG, people: MINI_PEOPLE, catalog: SITE_CATALOG });
    expect(r.ok ? [] : r.errors.map((e) => [e.code, e.at])).toEqual([['site_unreachable', [8, 25]]]);
  });

  it('site_unreachable вместо spot_unreachable для капсулы, закрытой стеной', () => {
    const shut = mutateYaml(ROUTES_OFFICE, (d) => (d.grid = d.grid.replace('#####...######', '##############')));
    const r = loadOfficeBundle({ office: shut, rules: MINI_RULES, config: MINI_CONFIG, people: MINI_PEOPLE, catalog: SITE_CATALOG });
    expect(r.ok ? [] : r.errors.map((e) => [e.code, e.at])).toEqual([['site_unreachable', [5, 2]], ['site_unreachable', [9, 2]]]);
  });

  it('site_unreachable: точка у двери автобуса недостижима (спека транспорта 3.8)', () => {
    const cut = mutateYaml(ROUTES_OFFICE, (d) => {
      d.site.grid = d.site.grid.replace('\n-------------------DDD', '\n-=-----------------DDD').replace('\n--SSSSS', '\n=-SSSSS');
    });
    const r = loadOfficeBundle({ office: cut, rules: MINI_RULES, config: MINI_CONFIG, people: MINI_PEOPLE, catalog: SITE_CATALOG });
    expect(r.ok ? [] : r.errors.map((e) => [e.code, e.at])).toEqual([['site_unreachable', [-2, 17]]]);
  });

  it('site_unreachable: спальное место парка, закрытое скамейками (спека сна 5.1)', () => {
    const shut = mutateYaml(ROUTES_OFFICE, (d) => {
      d.site.legend.b = 'bench';
      const rows: string[] = d.site.grid.trimEnd().split('\n');
      rows[11] = '<b' + rows[11]!.slice(2); // справа от спального места (−3, 10)
      rows[12] = 'b' + rows[12]!.slice(1); // под ним; сверху — спинка
      d.site.grid = rows.join('\n') + '\n';
    });
    const r = loadOfficeBundle({ office: shut, rules: MINI_RULES, config: MINI_CONFIG, people: MINI_PEOPLE, catalog: SITE_CATALOG });
    expect(r.ok ? [] : r.errors.map((e) => [e.code, e.at])).toEqual([['site_unreachable', [-3, 10]]]);
  });
});
