import type { Person } from './config.ts';
import type { MapError } from './errors.ts';
import { isPortalSpot, type WorldMap } from './world-map.ts';

const DIRS: [number, number][] = [[0, -1], [1, 0], [0, 1], [-1, 0]];

// BFS по транзитным клеткам от start (start — сам транзитный).
export function reachableFrom(map: WorldMap, start: [number, number]): Uint8Array {
  const seen = new Uint8Array(map.size);
  const [sx, sy] = start;
  if (!map.isTransit(sx, sy)) return seen;
  const queue = [map.index(sx, sy)];
  seen[queue[0]!] = 1;
  for (let head = 0; head < queue.length; head++) {
    const [x, y] = map.cell(queue[head]!);
    for (const [dx, dy] of DIRS) {
      const nx = x + dx;
      const ny = y + dy;
      if (!map.isTransit(nx, ny)) continue; // isTransit проверяет и границы: индекс считается только внутри карты
      const ni = map.index(nx, ny);
      if (seen[ni]) continue;
      seen[ni] = 1;
      queue.push(ni);
    }
  }
  return seen;
}

// Структурная валидация (спека 5.5): то, что не проверил разбор office.yaml. Ошибки людей — в файле людей
// (people.yaml или старое место, спека хостинга 3.1).
export function validateWorld(map: WorldMap, people: readonly Person[], file = 'office.yaml', peopleFile = 'people.yaml'): MapError[] {
  const errors: MapError[] = [];
  const err = (code: string, message: string, at?: [number, number]) => errors.push(at ? { file, code, message, at } : { file, code, message });
  const perr = (code: string, message: string) => errors.push({ file: peopleFile, code, message });

  if (map.entrances.length === 0) err('entrance_missing', 'нет клетки входа E');
  if (map.entrances.length > 1) err('entrance_multiple', `входов ${map.entrances.length}, в MVP поддерживается один`, map.entrances[1]);

  const pods = map.zones.filter((z) => z.kind === 'pod');
  if (pods.length < people.length) perr('pods_too_few', `углов (zone kind: pod) ${pods.length}, людей в конфиге ${people.length}`);
  const podOwner = new Map<string, string>();
  for (const p of people) {
    const z = map.zones.find((zone) => zone.id === p.pod);
    if (!z) perr('person_pod_missing', `people.${p.id}.pod: зоны «${p.pod}» нет в office.yaml`);
    else if (z.kind !== 'pod') perr('person_pod_kind', `people.${p.id}.pod: зона «${p.pod}» имеет kind ${z.kind}, нужен pod`);
    const other = podOwner.get(p.pod);
    if (other) perr('pod_shared', `угол «${p.pod}» назначен и ${other}, и ${p.id}`);
    podOwner.set(p.pod, p.id);
  }
  for (const z of pods) {
    const n = map.spotsInZone(z.id).filter((s) => s.tags.includes('owner_seat')).length;
    if (n !== 1) err('owner_seat_count', `в углу «${z.id}» мест owner_seat: ${n}, нужно ровно 1`, [z.rect[0], z.rect[1]]);
  }

  const entrance = map.entrances[0];
  if (entrance) {
    const [ex, ey] = entrance;
    if (!map.isTransit(ex, ey)) {
      // Место или блок на самом входе: BFS пуст, и каждое место дало бы spot_unreachable — одна точная ошибка вместо потока.
      err('entrance_blocked', 'клетка входа непроходима (на ней место или блокирующий предмет)', [ex, ey]);
      return errors;
    }
    if (!DIRS.some(([dx, dy]) => map.isTransit(ex + dx, ey + dy))) err('entrance_enclosed', 'у входа нет проходимой соседней клетки (вход в стене?)', [ex, ey]);
    const seen = reachableFrom(map, entrance);
    const reach = (x: number, y: number) => map.inBounds(x, y) && seen[map.index(x, y)] === 1;
    const near = (x: number, y: number) => DIRS.some(([dx, dy]) => reach(x + dx, y + dy));
    for (const s of map.spots) {
      if (near(s.x, s.y)) continue;
      // Место-портал (остановка, капсула) — точка появления и ухода (спека маршрутов 3.8).
      if (isPortalSpot(s)) err('site_unreachable', `место ${s.id} (${s.tags.join(', ')}) недостижимо от входа`, [s.x, s.y]);
      else err('spot_unreachable', `место ${s.id} (${s.pose}) недостижимо от входа`, [s.x, s.y]);
    }
    const p = map.portals;
    const cells: [string, [number, number] | null][] = [
      ['спуск в метро', p.metro],
      ['точка у двери автобуса', map.transport?.bus?.door ?? null], // спека транспорта 3.8
      ...p.carSpots.map((c): [string, [number, number]] => ['место парковки', c]),
    ];
    for (const [what, c] of cells) if (c && !reach(c[0], c[1])) err('site_unreachable', `${what}: клетка недостижима от входа`, c);
  }
  return errors;
}
