import { describe, expect, it } from 'vitest';
import { parseOffice } from '../src/index.ts';
import { SITE_OFFICE, miniCatalog, mutateYaml, office, siteCatalog, siteOffice } from './fixtures.ts';

const codes = (text: string, cat = siteCatalog()) => {
  const r = parseOffice(text, cat);
  return r.ok ? [] : r.errors.map((e) => e.code);
};
const withSite = (fn: (site: any) => void) => mutateYaml(SITE_OFFICE, (d) => fn(d.site));
// Правка строк сетки участка по номеру.
const withRows = (fn: (rows: string[]) => void) =>
  withSite((s) => {
    const rows = s.grid.trimEnd().split('\n');
    fn(rows);
    s.grid = rows.join('\n') + '\n';
  });
// Маркер без on в клетке (0, 3) участка (мир (−3, 2)): имя маркера разбор участка не проверяет (решение 13 плана сна).
const MARKED = withSite((s) => {
  s.legend.x = { marker: 'gate' };
  const rows: string[] = s.grid.trimEnd().split('\n');
  rows[3] = 'x' + rows[3]!.slice(1);
  s.grid = rows.join('\n') + '\n';
});

describe('участок: разбор', () => {
  const s = siteOffice().site!;
  const at = (sx: number, sy: number) => s.terrain[sy * 20 + sx];

  it('car_spot: facing down у маркера; facing у другого маркера или left — marker_facing (спека транспорта 3.3)', () => {
    const down = siteOffice(withSite((s) => (s.legend.c = { marker: 'car_spot', on: 'sidewalk', facing: 'down' }))).site!;
    expect(down.markers).toContainEqual({ name: 'car_spot', x: 14, y: 0, facing: 'down' });
    expect(codes(withSite((s) => (s.legend.x = { marker: 'gate', facing: 'up' })))).toEqual(['marker_facing']);
    expect(codes(withSite((s) => (s.legend.c = { marker: 'car_spot', on: 'sidewalk', facing: 'left' })))).toEqual(['marker_facing']);
  });

  it('участок, здание и кадр — в мировых клетках (левее и выше здания — отрицательные)', () => {
    expect(s.rect).toEqual([-3, -1, 20, 14]);
    expect(s.building).toEqual([0, 0, 14, 9]);
    expect(s.view).toEqual([-1, -1, 16, 13]);
  });

  it('земля: building, заливка под предметом и маркером без on, on у предмета и маркера', () => {
    expect(at(3, 1)).toBe('building');
    expect(at(0, 1)).toBe('grass'); // под деревом — fill
    expect(siteOffice(MARKED).site!.terrain[3 * 20 + 0]).toBe('grass'); // маркер без on
    expect(at(17, 1)).toBe('sidewalk'); // тротуар у угла здания
    expect(at(5, 10)).toBe('sidewalk'); // скамейка on: sidewalk
    expect(at(0, 12)).toBe('road'); // декаль on: road
    expect(at(8, 10)).toBe('sidewalk'); // { terrain, tags }
  });

  it('предметы, декали, маркеры и теги — в мировых клетках', () => {
    expect(s.items.find((i) => i.item === 'tree')).toMatchObject({ uid: 'site:tree@-3,0', x: -3, y: 0, facing: null, variant: 1 });
    expect(s.items.find((i) => i.item === 'bench')).toMatchObject({ x: 2, y: 9 });
    const dashes = s.items.filter((i) => i.item === 'lane_dash');
    expect(dashes).toHaveLength(20);
    expect(new Set(dashes.map((i) => i.y))).toEqual(new Set([11]));
    expect(dashes[0]!.x).toBe(-3);
    expect(s.markers).toEqual([]);
    expect(siteOffice(MARKED).site!.markers).toEqual([{ name: 'gate', x: -3, y: 2 }]);
    expect(s.tags).toEqual([{ x: 5, y: 9, tags: ['stop'] }]);
  });

  it('site.fill меняет землю по умолчанию', () => {
    const t = siteOffice(withSite((x) => (x.fill = 'sidewalk'))).site!.terrain;
    expect(t[1 * 20 + 0]).toBe('sidewalk');
  });

  it('офис без site — поля нет, остальное как раньше', () => {
    expect(office().site).toBeUndefined();
  });
});

describe('участок: ошибки (спека 5.2)', () => {
  it('site_ragged', () => {
    expect(codes(withRows((r) => (r[0] = ',,,')))).toEqual(['site_ragged']);
  });

  it('site_unknown: символ, имя в легенде, on, fill, terrain', () => {
    expect(codes(withRows((r) => (r[3] = '?' + r[3]!.slice(1))))).toContain('site_unknown');
    expect(codes(withSite((s) => (s.legend.q = 'lava')))).toContain('site_unknown');
    expect(codes(withSite((s) => (s.legend.b = { item: 'bench', on: 'lava' })))).toContain('site_unknown');
    expect(codes(withSite((s) => (s.legend.c = { marker: 'car_spot', on: 'lava' })))).toContain('site_unknown');
    expect(codes(withSite((s) => (s.legend.k = { terrain: 'lava' })))).toContain('site_unknown');
    expect(codes(withSite((s) => (s.fill = 'lava')))).toContain('site_unknown');
    expect(codes(withSite((s) => (s.legend.q = { item: 'nope' })))).toContain('site_unknown');
  });

  it('facing и variant предмета участка проверяются как в здании', () => {
    expect(codes(withSite((s) => (s.legend.q = { item: 'chair' })))).toContain('facing_required');
    expect(codes(withSite((s) => (s.legend.q = { item: 'bench', variant: 5 })))).toContain('unknown_variant');
  });

  it('site_building_missing, site_building_multiple, site_building_size', () => {
    expect(codes(withSite((s) => (s.grid = s.grid.replaceAll('@', ','))))).toEqual(['site_building_missing']);
    expect(codes(withRows((r) => (r[4] = ',,,@@,@@@@@@@@@@@,,,')))).toEqual(['site_building_multiple']);
    expect(codes(withRows((r) => (r[9] = ',,,,,,,,,,,,,,,,,,,,')))).toEqual(['site_building_size']);
  });

  it('incomplete_footprint у многоклеточного предмета участка', () => {
    expect(codes(withRows((r) => (r[2] = r[2]!.replace('TT', ',,'))))).toContain('incomplete_footprint');
  });

  it('site_view: не задан или выходит за участок', () => {
    expect(codes(withSite((s) => delete s.view))).toEqual(['site_view']);
    expect(codes(withSite((s) => (s.view = [10, 0, 16, 13])))).toEqual(['site_view']);
  });

  it('site_catalog: в каталоге нет фасада, двери или нижнего ряда стен', () => {
    expect(codes(SITE_OFFICE, miniCatalog())).toContain('site_catalog');
  });
});
