import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
import { buildWorldMap, loadCatalog, parseOffice } from '../src/index.ts';

const read = (rel: string) => readFileSync(new URL(rel, import.meta.url), 'utf8');
const cat = loadCatalog(read('../../../catalog/limezu/catalog.yaml'));
if (!cat.ok) throw new Error(JSON.stringify(cat.errors));
const plan = (name: string) => {
  const l = parseOffice(read(`../../../offices/${name}/office.yaml`), cat.value);
  if (!l.ok) throw new Error(JSON.stringify(l.errors));
  const m = buildWorldMap(l.value, cat.value);
  if (!m.ok) throw new Error(JSON.stringify(m.errors));
  return m.value.transport!;
};

describe('транспорт офисов (спека транспорта 6)', () => {
  for (const [name, n] of [['demo', 8], ['team', 8], ['local', 3]] as const) {
    it(`${name}: маршруты всех ${n} мест для всех форм — въезд и выезд`, () => {
      const t = plan(name);
      expect(t.shapes).toHaveLength(26);
      expect(t.spots).toHaveLength(n);
      for (const sp of t.spots) {
        expect(Object.keys(sp.arrive), sp.key).toEqual(['4x4', '5x5', '5x4']);
        expect(Object.keys(sp.depart), sp.key).toEqual(['4x4', '5x5', '5x4']);
      }
    });
  }

  it('demo: полоса — ряды 27–28, проезд — x 39,5; сдвиги у крайнего правого места и у нижнего ряда (спека 4.1)', () => {
    const t = plan('demo');
    const sp = (k: string) => t.spots.find((s) => s.key === k)!;
    // Въезд — ряды 24–26, полоса — 27–28 (ry = 27): устье отпускается, когда нижний край контура поднялся до ry —
    // центр (39,5; 25), там отрезок по проезду делится (спека 4.3).
    expect(sp('41,7').arrive['4x4']!.map((s) => [s.from, s.to, s.mouth, s.lot])).toEqual([
      [[76, 28], [44, 28], false, false],
      [[44, 28], [39.5, 28], true, true],
      [[39.5, 28], [39.5, 25], true, true],
      [[39.5, 25], [39.5, 14], false, true],
      [[40, 14], [42.5, 14], false, true],
      [[42.5, 14], [42.5, 9.5], false, true],
    ]);
    // Верхний ряд: ось ряда 14 (sy + 7); длина 5 на оси задела бы место под ним (ряд 16) — на место на 0,5 выше оси.
    expect(sp('41,7').arrive['5x5']!.at(-1)!.from).toEqual([42.5, 13.5]);
    const right = sp('50,7').arrive['5x5']!;
    expect([right.at(-2)!.to, right.at(-1)!.from]).toEqual([[50.5, 14], [51.5, 13.5]]); // на место — на клетку раньше
    const low = sp('41,16');
    expect(low.arrive['5x5']!.at(-2)!.to).toEqual([42.5, 23]); // нижний ряд: ось ряда 23, под ним тротуар (ряд 24)
    expect(low.arrive['5x5']!.at(-1)!.from).toEqual([42.5, 21.5]); // на место — на 1,5 выше оси ряда
    expect(low.depart['5x5']![0]).toMatchObject({ from: [42.5, 18.5], to: [42.5, 21.5], reverse: true, speed: 1.5 });
    expect(t.bus).toMatchObject({ rect: [1, 27, 8, 30], center: [4.5, 28.5], door: [1, 26] });
  });

  // Ряд места (спека транспорта 4.1): кадр сбоку — 3 ряда над низом контура (крыша выше контура, 3.5). У мест up ось
  // ряда — sy + 7, и крыша едущей по ряду машины не ложится на разметку места; ни один кадр сбоку на парковке — ни на
  // какое место.
  for (const name of ['demo', 'team', 'local']) {
    it(`${name}: машина боком на парковке кадром не заходит на места, ось ряда у места up — sy + 7`, () => {
      const t = plan(name);
      const spotCell = new Set(t.spots.flatMap((s) => [0, 1, 2, 3, 4].flatMap((j) => [0, 1, 2].map((i) => `${s.spot[0] + i},${s.spot[1] + j}`))));
      for (const sp of t.spots)
        for (const shape of t.shapes) {
          const key = `${shape.side}x${shape.top}`;
          const segs = [...sp.arrive[key]!, ...sp.depart[key]!].filter((s) => (s.dir === 'left' || s.dir === 'right') && s.speed !== 8);
          expect(segs.length, `${sp.key} ${key}`).toBeGreaterThan(0);
          for (const s of segs) {
            expect(s.from[1], `${sp.key} ${key}`).toBe(sp.spot[1] + 7);
            for (const [x, y] of [s.from, s.to]) {
              const [x0, x1, y0] = [x - shape.side / 2, x + shape.side / 2, y + 1 - 3]; // кадр — до низа контура y + 1
              for (let cy = Math.floor(y0); cy < y + 1; cy++)
                for (let cx = Math.floor(x0); cx < Math.ceil(x1); cx++) expect(spotCell.has(`${cx},${cy}`), `${sp.key} ${key} (${cx}, ${cy})`).toBe(false);
            }
          }
        }
    });
  }

  it('local: карман и дверь автобуса, въезд у левого края парковки', () => {
    const t = plan('local');
    expect(t.bus).toMatchObject({ rect: [-3, 21, 4, 24], door: [-3, 20] });
    expect(t.spots[0]!.arrive['4x4']![2]).toMatchObject({ from: [27.5, 22], dir: 'up' });
  });
});
