import { describe, expect, it } from 'vitest';
import { fnv1a } from '@pixeloffice/core';
import { advance, iso, makeRuntime } from './helpers.ts';

// Первая видимая позиция каждого из ids (точная: на машине и автобусе появляются в дробной точке у двери).
function firstSeen(ids: string[]) {
  const { rt, clock } = makeRuntime();
  const src = rt.sourceByName('manual')!;
  rt.ingestFromSource(src, ids.map((entityId) => ({ type: 'status' as const, entityId, status: 'online' as const, at: iso(clock) })));
  const out: Record<string, [number, number]> = {};
  for (let i = 0; i < 800 && Object.keys(out).length < ids.length; i++) {
    advance(rt, clock, 50);
    for (const c of rt.world.characters()) out[c.id] ??= [c.x, c.y];
  }
  return { out, map: rt.office.bundle.map };
}
// В шаге от точки: появился и сделал первый шаг в том же тике.
const near = (p: [number, number] | undefined, q: readonly [number, number]) => p !== undefined && Math.abs(p[0] - q[0]) + Math.abs(p[1] - q[1]) <= 0.35;

describe('способ добираться в симуляции (спека маршрутов 4.6, спека транспорта 4.5)', () => {
  it('p1 — под кузовом своей машины, p3 — у двери автобуса, p5 (park) и p6 — у метро (спека сна 5.2)', () => {
    const { out, map } = firstSeen(['p1', 'p3', 'p5', 'p6']);
    expect(map.transport!.spots.some((s) => near(out['p1'], s.seat))).toBe(true);
    expect(near(out['p3'], map.transport!.bus!.door)).toBe(true);
    expect(near(out['p5'], map.portals.metro!)).toBe(true);
    expect(near(out['p6'], map.portals.metro!)).toBe(true);
  });

  it('p5 (park), уйдя в offline, ложится на свою боковую скамейку и остаётся видимым (спека сна 5.3)', () => {
    const { rt, clock } = makeRuntime();
    const src = rt.sourceByName('manual')!;
    rt.ingestFromSource(src, [{ type: 'status', entityId: 'p5', status: 'online', at: iso(clock) }]);
    advance(rt, clock, 40_000);
    rt.ingestFromSource(src, [{ type: 'status', entityId: 'p5', status: 'offline', at: iso(clock) }]);
    advance(rt, clock, 60_000);
    const map = rt.office.bundle.map;
    const c = rt.world.characters().find((x) => x.id === 'p5');
    expect(c).toMatchObject({ pose: 'sleep', facing: 'down' });
    const ids = map.portals.parkSleep;
    expect(map.spotAt(c!.x, c!.y)?.id).toBe(ids[fnv1a('p5') % ids.length]);
  });
});
