import type { WorldMap } from '../world-map.ts';
import { MinHeap } from './heap.ts';

export type Cell = [number, number];

// Фиксированный порядок соседей: вверх, вправо, вниз, влево.
const DIRS: Cell[] = [[0, -1], [1, 0], [0, 1], [-1, 0]];

// occupied — клетки, занятые сейчас (стоящие машины, спека транспорта 4.7.2), поверх статичных блоков: непроходимы и как
// цель. Начальная клетка не проверяется — стоящий под машиной выходит из-под неё.
export function findPath(map: WorldMap, from: Cell, to: Cell, occupied?: (x: number, y: number) => boolean): Cell[] | null {
  const [fx, fy] = from;
  const [tx, ty] = to;
  if (!map.inBounds(fx, fy) || map.isBlocked(tx, ty)) return null;
  if (fx === tx && fy === ty) return [[fx, fy]];
  const size = map.size;
  const start = map.index(fx, fy);
  const goal = map.index(tx, ty);
  const g = new Float64Array(size).fill(Infinity);
  const came = new Int32Array(size).fill(-1);
  const closed = new Uint8Array(size);
  // Манхэттен: минимальная цена клетки 1 — эвристика допустима.
  const h = (i: number) => {
    const [x, y] = map.cell(i);
    return Math.abs(x - tx) + Math.abs(y - ty);
  };
  const open = new MinHeap<number>();
  let seq = 0;
  g[start] = 0;
  open.push(start, h(start), h(start), seq++);
  while (open.size > 0) {
    const cur = open.pop()!;
    if (cur === goal) break;
    if (closed[cur]) continue;
    closed[cur] = 1;
    const [cx, cy] = map.cell(cur);
    for (const [dx, dy] of DIRS) {
      const nx = cx + dx;
      const ny = cy + dy;
      if (!map.inBounds(nx, ny)) continue;
      const ni = map.index(nx, ny);
      if (closed[ni]) continue;
      if (ni !== goal && !map.isTransit(nx, ny)) continue; // места — только как цель
      if (occupied?.(nx, ny)) continue;
      const ng = g[cur]! + map.cost(nx, ny);
      if (ng < g[ni]!) {
        g[ni] = ng;
        came[ni] = cur;
        open.push(ni, ng + h(ni), h(ni), seq++);
      }
    }
  }
  if (came[goal] === -1) return null;
  const path: Cell[] = [];
  for (let i = goal; i !== start; i = came[i]!) path.push(map.cell(i));
  path.push([fx, fy]);
  return path.reverse();
}
