import type { CarEngine, Facing, Frame, VehicleKit } from '@pixeloffice/protocol';
import type { VehiclesDef } from './catalog.ts';

// Форма машины (спека транспорта 3.5): контур сбоку — side × 2 клетки, сверху — 2 × top. Считается из кадров модели.
export type CarShape = { side: number; top: number };
export const shapeKey = (s: CarShape): string => `${s.side}x${s.top}`;

export function carShapes(v: VehiclesDef, ts: number): CarShape[] {
  return v.cars.map((c) => ({ side: c.left[2] / ts, top: c.up[3] / ts }));
}

// Различные формы в порядке первого появления: маршруты строятся и проверяются для каждой (спека транспорта 4.1).
export function distinctShapes(list: readonly CarShape[]): CarShape[] {
  const seen = new Map<string, CarShape>();
  for (const s of list) if (!seen.has(shapeKey(s))) seen.set(shapeKey(s), s);
  return [...seen.values()];
}

const DIRS: readonly Facing[] = ['up', 'down', 'left', 'right'];

// Голос мотора модели без поля engine в каталоге (спека звуков транспорта §4.1).
export const DEFAULT_CAR_ENGINE: CarEngine = { sound: 'sedan', rate: 1 };

// Кадры и голоса моторов для hello (спека транспорта 5.1, спека звуков транспорта §4.1): sheet — URL листа.
export function vehicleKit(v: VehiclesDef, sheets: Record<string, string>, assetUrl: (path: string) => string): VehicleKit {
  const sheet = assetUrl(sheets[v.sheet]!);
  const frame = ([x, y, w, h]: [number, number, number, number]): Frame => ({ sheet, x, y, w, h });
  return {
    cars: v.cars.map((c) => Object.fromEntries(DIRS.map((d) => [d, frame(c[d])])) as Record<Facing, Frame>),
    bus: frame(v.bus.left),
    busLift: v.bus.lift,
    carLift: v.carLift,
    engines: v.cars.map((c) => ({ ...(c.engine ?? DEFAULT_CAR_ENGINE) })),
  };
}
