import { describe, expect, it } from 'vitest';
import { assignCarSpots, buildWorldMap, commuteFor, portalOf } from '../src/index.ts';
import { ROUTES_OFFICE, WORLD_OFFICE, miniCatalog, mutateYaml, office, routesOffice, siteCatalog } from './fixtures.ts';

const mapOf = (text = ROUTES_OFFICE) => {
  const r = buildWorldMap(routesOffice(text), siteCatalog());
  if (!r.ok) throw new Error(JSON.stringify(r.errors));
  return r.value;
};

describe('commuteFor: запасной путь — метро (спека маршрутов 3.1, 4.6.2)', () => {
  it('точки способов есть — способ как в конфиге', () => {
    const m = mapOf();
    for (const c of ['car', 'bus', 'metro', 'park'] as const) expect(commuteFor(m, c)).toBe(c);
  });
  it('нет мест парковки, остановки или боковых скамеек — метро', () => {
    const bare = mutateYaml(ROUTES_OFFICE, (d) => {
      d.site.grid = d.site.grid.replace('PPPcPP', 'PPPPPP').replaceAll('<', ',').replace('--SSSSS', '-------');
    });
    const m = mapOf(bare);
    expect((['car', 'bus', 'park', 'metro'] as const).map((c) => commuteFor(m, c))).toEqual(['metro', 'metro', 'metro', 'metro']);
  });
});

describe('assignCarSpots (спека маршрутов 4.6.1)', () => {
  const spots: [number, number][] = [[0, 0], [3, 0], [6, 0]];
  it('детерминировано и без повторов, пока мест хватает; порядок ids не важен', () => {
    const a = assignCarSpots(['p1', 'p2', 'p3'], spots);
    expect(new Set([...a.values()].map((c) => c.join(','))).size).toBe(3);
    expect(assignCarSpots(['p3', 'p1', 'p2'], spots)).toEqual(a);
  });
  it('людей больше, чем мест, — лишние (последние по id) мест не получают: места не делятся (спека транспорта 3.8)', () => {
    const a = assignCarSpots(['p5', 'p1', 'p2', 'p4', 'p3'], spots);
    expect([...a.keys()]).toEqual(['p1', 'p2', 'p3']);
    expect(new Set([...a.values()].map((c) => c.join(','))).size).toBe(3);
    expect(assignCarSpots(['p1'], []).size).toBe(0);
  });
});

describe('portalOf (спека маршрутов 4.3)', () => {
  const m = mapOf();
  const h = (extra: object = {}) => ({ id: 'p', kind: 'human' as const, ...extra });
  it('человек при участке — по commute; по умолчанию метро', () => {
    expect(portalOf(m, h())).toEqual({ kind: 'cell', key: 'metro', cell: [8, 25] });
    expect(portalOf(m, h({ commute: 'car', carSpot: [19, 9] }))).toEqual({ kind: 'cell', key: 'car:19,9', cell: [19, 9] });
    expect(portalOf(m, h({ commute: 'car' }))).toEqual({ kind: 'cell', key: 'car:19,9', cell: [19, 9] }); // без закрепления (не от сервера) — запасное первое место
    expect(portalOf(m, h({ commute: 'park' }))).toEqual({ kind: 'cell', key: 'metro', cell: [8, 25] }); // приходит из метро (спека сна 5.2)
    expect(portalOf(m, h({ commute: 'bus' }))).toEqual({ kind: 'spots', key: 'bus', spots: ['site:bus_stop@-1,17#0', 'site:bus_stop@-1,17#1'] });
  });
  it('агент — капсулы; без капсул — точка у двери; без участка — E', () => {
    expect(portalOf(m, { id: 'g', kind: 'agent', ownerId: 'p' })).toEqual({ kind: 'spots', key: 'dock', spots: ['agent_dock@5,1#0', 'agent_dock@5,1#1'] });
    const noDock = mapOf(mutateYaml(ROUTES_OFFICE, (d) => (d.grid = d.grid.replaceAll('KKKKKK', '......'))));
    expect(portalOf(noDock, { id: 'g', kind: 'agent' })).toEqual({ kind: 'cell', key: 'door', cell: [6, 17] });
    const plain = buildWorldMap(office(), miniCatalog());
    if (!plain.ok) throw new Error(JSON.stringify(plain.errors));
    expect(portalOf(plain.value, h({ commute: 'car' }))).toEqual({ kind: 'cell', key: 'door', cell: [6, 6] });
  });
  it('agents.arrival: metro — из метро даже при капсулах; door — всегда дверь', () => {
    const metro = mapOf(mutateYaml(ROUTES_OFFICE, (d) => (d.agents = { arrival: 'metro' })));
    expect(portalOf(metro, { id: 'g', kind: 'agent', ownerId: 'p' })).toEqual({ kind: 'cell', key: 'metro', cell: [8, 25] });
    const door = mapOf(mutateYaml(ROUTES_OFFICE, (d) => (d.agents = { arrival: 'door' })));
    expect(portalOf(door, { id: 'g', kind: 'agent' })).toEqual({ kind: 'cell', key: 'door', cell: [6, 17] });
  });
  it('agents.arrival: metro без участка — ошибка загрузки agents_arrival_metro', () => {
    const r = buildWorldMap(office(mutateYaml(WORLD_OFFICE, (d) => (d.agents = { arrival: 'metro' }))), miniCatalog());
    expect(r.ok).toBe(false);
    if (!r.ok) expect(r.errors.map((e) => e.code)).toContain('agents_arrival_metro');
  });
});
