import type { WorldMap } from '@pixeloffice/core';

// 8-направленный A* арены (спека диагоналей 5.1): стоимость клетки 1 в любом направлении — путь
// оптимален по времени (один шаг — один кулдаун), эвристика Чебышёва допустима при единичной цене
// диагонали. core не трогаем: его findPath офисный, 4-направленный, и его поведение — часть спеки
// офисной симуляции. Правило среза угла — в расширении соседей: диагональное ребро допустимо, только
// когда свободна хотя бы одна ортогональная клетка; «занято» — непроходимо или живой агент (occupied).

export type Cell = [number, number];

// Соседи по кругу: кардиналы и диагонали, фиксированный порядок — путь детерминирован (решение плана 3).
const DIRS: Cell[] = [
  [0, -1], [1, -1], [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1],
];

// Открытый список — мини-куча по (f, h, номер клетки, порядок вставки): меньше оценка, ближе
// к цели, дальше — детерминированный порядок. Аналог MinHeap из core (тот не экспортируется
// публично), упрощён до нужного: числа в массивах.
class OpenHeap {
  private readonly f: number[] = [];
  private readonly h: number[] = [];
  private readonly item: number[] = [];

  push(i: number, f: number, h: number, seq: number): void {
    this.f.push(f);
    this.h.push(h);
    this.item.push(i * 1e9 + seq); // клетка и порядок вставки одной сортировкой: seq < 1e9
    let c = this.f.length - 1;
    while (c > 0) {
      const p = (c - 1) >> 1;
      if (this.less(c, p)) this.swap(c, p);
      else break;
      c = p;
    }
  }

  pop(): number {
    const top = this.item[0]!;
    const last = this.f.length - 1;
    this.swap(0, last);
    this.f.pop();
    this.h.pop();
    this.item.pop();
    let c = 0;
    for (;;) {
      const l = 2 * c + 1;
      const r = l + 1;
      let m = c;
      if (l < this.f.length && this.less(l, m)) m = l;
      if (r < this.f.length && this.less(r, m)) m = r;
      if (m === c) break;
      this.swap(c, m);
      c = m;
    }
    return Math.floor(top / 1e9);
  }

  get size(): number {
    return this.f.length;
  }

  private less(a: number, b: number): boolean {
    return this.f[a]! < this.f[b]! || (this.f[a]! === this.f[b]! && this.h[a]! < this.h[b]!) ||
      (this.f[a]! === this.f[b]! && this.h[a]! === this.h[b]! && this.item[a]! < this.item[b]!);
  }

  private swap(a: number, b: number): void {
    [this.f[a], this.f[b]] = [this.f[b], this.f[a]!];
    [this.h[a], this.h[b]] = [this.h[b], this.h[a]!];
    [this.item[a], this.item[b]] = [this.item[b], this.item[a]!];
  }
}

// Путь от старта до цели включительно либо null — формат офисного findPath (решение плана 5).
// occupied — клетки, занятые живыми агентами: непроходимы и как цель (moveTo в занятое — unreachable).
export function findPath8(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.inBounds(tx, ty)) return null;
  if (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 даже по диагонали — эвристика допустима и консистентна (спека диагоналей 5.2).
  const h = (i: number): number => {
    const [x, y] = map.cell(i);
    return Math.max(Math.abs(x - tx), Math.abs(y - ty));
  };
  const open = new OpenHeap();
  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] || map.isBlocked(nx, ny)) continue;
      if (occupied?.(nx, ny)) continue; // живой агент — препятствие и как цель (спека диагоналей 5.3)
      if (dx !== 0 && dy !== 0) {
        // Правило среза угла (спека диагоналей 5.3): диагональное ребро допустимо, когда свободна
        // хотя бы одна ортогональная клетка.
        const busyA = map.isBlocked(cx + dx, cy) || occupied?.(cx + dx, cy) === true;
        const busyB = map.isBlocked(cx, cy + dy) || occupied?.(cx, cy + dy) === true;
        if (busyA && busyB) continue;
      }
      const ng = g[cur]! + 1; // стоимость клетки 1 в любом направлении (спека диагоналей 5.2)
      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();
}
