import { assignCarSpots, commuteFor, fnv1a, type Commute, type OfficeBundle } from '@pixeloffice/core';
import type { Pose } from '@pixeloffice/protocol';

export type OfficeReport = {
  building: { w: number; h: number };
  site: { x: number; y: number; w: number; h: number } | null;
  zones: { id: string; kind: 'pod' | 'meeting' | 'common'; cells: number; spots: Partial<Record<Pose, number>> }[];
  people: { id: string; name: string; pod: string; commute: Commute; effectiveCommute: Commute; parking?: [number, number]; sleepSpot?: string }[];
  portals: { carSpots: number; parkSleep: number; metro: boolean; busStop: boolean; busBay: boolean; docks: number };
};

// Что собралось из набора (спека хостинга 7.4): ИИ сверяет с тем, что хотел человек. Недостижимость мест — уже ошибки
// проверки (spot_unreachable, site_unreachable), сюда не дублируется.
export function officeReport(b: OfficeBundle): OfficeReport {
  const { map, layout, config } = b;
  const p = map.portals;
  const site = layout.site?.rect;
  const effective = (c: Commute) => commuteFor(map, c);
  const drivers = config.people.filter((x) => effective(x.commute) === 'car').map((x) => x.id);
  const parking = assignCarSpots(drivers, p.carSpots);
  return {
    building: { w: layout.width, h: layout.height },
    site: site ? { x: site[0], y: site[1], w: site[2], h: site[3] } : null,
    zones: map.zones.map((z) => {
      const spots: Partial<Record<Pose, number>> = {};
      for (const s of map.spotsInZone(z.id)) spots[s.pose] = (spots[s.pose] ?? 0) + 1;
      return { id: z.id, kind: z.kind, cells: z.rect[2] * z.rect[3], spots };
    }),
    people: config.people.map((x) => {
      const eff = effective(x.commute);
      const car = parking.get(x.id);
      // Спальное место — предпочтительное (fnv1a(id) % n): занято — в мире ляжет на следующее по кругу.
      const bed = eff === 'park' && p.parkSleep.length ? p.parkSleep[fnv1a(x.id) % p.parkSleep.length] : undefined;
      return { id: x.id, name: x.name, pod: x.pod, commute: x.commute, effectiveCommute: eff, ...(car ? { parking: car } : {}), ...(bed ? { sleepSpot: bed } : {}) };
    }),
    portals: { carSpots: p.carSpots.length, parkSleep: p.parkSleep.length, metro: p.metro !== null, busStop: p.busWait.length > 0, busBay: map.transport?.bus != null, docks: p.docks.length },
  };
}
