import type { Facing, LabelPlacement, Pose } from '@pixeloffice/protocol';
import { itemView, type Catalog } from './catalog.ts';
import { fail, ok, type MapError, type Result } from './errors.ts';
import { zoneAt, type OfficeLayout, type Zone } from './office.ts';
import { buildTransport } from './sim/car-routes.ts';
import type { TransportPlan } from './sim/transport.ts';
import { BUILDING } from './site.ts';

// Тай-брейк по кодовым точкам: localeCompare зависит от локали и версии ICU, а порядок должен быть одинаков везде.
export const byCodePoint = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);

export type Spot = {
  id: string;
  x: number;
  y: number;
  facing: Facing;
  pose: Pose;
  offset: [number, number];
  label: LabelPlacement;
  fidgets: string[]; // бытовые анимации места (каталог), спека 5.2
  tags: string[];
  itemUid: string;
  zoneId: string | null;
};

// Места-порталы (спека маршрутов 4.3, спека сна 5.1): на них появляются, уходят или спят; цели правил их не выбирают.
export const PORTAL_TAGS: readonly string[] = ['bus_wait', 'agent_dock', 'park_sleep'];
export const isPortalSpot = (s: Spot): boolean => s.tags.some((t) => PORTAL_TAGS.includes(t));

// Капсула дока на карте (спека маршрутов 3.7, 4.6): место агента, его точка, клетки капсулы и тумбы, клетки пола перед
// капсулой (под нижним рядом тумбы, по столбцу), предмет и сдвиг рисования капсулы (пиксели внутри предмета, как в
// DockCapsuleDef.at) — для RenderedMap.docks.
// Точка места: клетка + сдвиг места в клетках (спека маршрутов 4.3) — там стоит персонаж на месте-портале.
export const spotPoint = (s: Pick<Spot, 'x' | 'y' | 'offset'>, tileSize: number): [number, number] => [s.x + s.offset[0] / tileSize, s.y + s.offset[1] / tileSize];

export type DockSpot = {
  spotId: string;
  point: [number, number];
  cells: [number, number][];
  plinth: [number, number][];
  front: [number, number][];
  item: { id: string; uid: string; x: number; y: number };
  at: [number, number];
};
export type MapPortals = {
  metro: [number, number] | null; // нижняя ступень спуска
  carSpots: [number, number][]; // клетки пути у водительской двери мест парковки (спека транспорта 3.3), в порядке маркеров
  busWait: string[]; // места bus_wait в порядке мест карты
  parkSleep: string[]; // спальные места парка — нижние клетки боковых скамеек участка (спека сна 5.1), в порядке мест карты
  docks: DockSpot[]; // капсулы в порядке мест карты
};

export class WorldMap {
  readonly originX: number; // мировая клетка левого верхнего угла карты (спека маршрутов 4.1)
  readonly originY: number;
  readonly width: number;
  readonly height: number;
  readonly spots: Spot[];
  readonly zones: Zone[];
  readonly entrances: [number, number][];
  readonly hiddenCells: [number, number][]; // скрытые клетки: нижняя ступень метро (спека маршрутов 4.4)
  readonly doorPoint: [number, number]; // точка у двери (спека маршрутов 4.3): при участке — второй ряд тротуара под проёмом
  readonly site: boolean; // у офиса есть участок
  readonly tileSize: number;
  readonly portals: MapPortals;
  readonly agentArrival: 'dock' | 'metro' | 'door'; // портал агентов (спека маршрутов 4.3): капсулы/метро/дверь
  readonly transport: TransportPlan | null; // транспорт участка (спека транспорта 4.1); без участка — null
  private readonly blocked: Uint8Array;
  private readonly costs: Uint8Array | null;
  private readonly hidden: Set<number>;
  private readonly terrain: (string | null)[] | null;
  private readonly byCell = new Map<number, Spot>();
  private readonly byId = new Map<string, Spot>();
  private readonly byZone = new Map<string, Spot[]>();
  private readonly byDock = new Map<string, DockSpot>();
  private readonly dockBody = new Map<number, DockSpot>(); // клетки капсул и тумб — их капсула
  private readonly dockArea = new Set<number>(); // они же и клетки пола перед капсулами

  constructor(init: {
    originX?: number;
    originY?: number;
    width: number;
    height: number;
    blocked: Uint8Array;
    cost?: Uint8Array;
    terrain?: (string | null)[];
    hidden?: [number, number][];
    spots: Spot[];
    zones: Zone[];
    entrances: [number, number][];
    doorPoint?: [number, number];
    site?: boolean;
    tileSize?: number;
    portals?: Partial<Omit<MapPortals, 'busWait'>>;
    agentArrival?: 'dock' | 'metro' | 'door';
    transport?: TransportPlan | null;
  }) {
    this.originX = init.originX ?? 0;
    this.originY = init.originY ?? 0;
    this.width = init.width;
    this.height = init.height;
    this.blocked = init.blocked;
    this.costs = init.cost ?? null;
    this.terrain = init.terrain ?? null;
    this.hiddenCells = init.hidden ?? [];
    this.hidden = new Set(this.hiddenCells.map(([x, y]) => this.index(x, y)));
    this.spots = [...init.spots].sort((a, b) => a.y - b.y || a.x - b.x || byCodePoint(a.id, b.id));
    this.zones = init.zones;
    this.entrances = init.entrances;
    this.doorPoint = init.doorPoint ?? init.entrances[0] ?? [0, 0];
    this.site = init.site ?? false;
    this.tileSize = init.tileSize ?? 16;
    this.transport = init.transport ?? null;
    this.agentArrival = init.agentArrival ?? 'dock';
    const order = new Map(this.spots.map((s, i) => [s.id, i]));
    this.portals = {
      metro: init.portals?.metro ?? null,
      carSpots: init.portals?.carSpots ?? [],
      busWait: this.spots.filter((s) => s.tags.includes('bus_wait')).map((s) => s.id),
      parkSleep: [...(init.portals?.parkSleep ?? [])].sort((a, b) => order.get(a)! - order.get(b)!),
      docks: [...(init.portals?.docks ?? [])].sort((a, b) => order.get(a.spotId)! - order.get(b.spotId)!),
    };
    for (const d of this.portals.docks) {
      this.byDock.set(d.spotId, d);
      for (const [x, y] of [...d.cells, ...d.plinth]) this.dockBody.set(this.index(x, y), d);
      for (const [x, y] of [...d.cells, ...d.plinth, ...d.front]) this.dockArea.add(this.index(x, y));
    }
    for (const s of this.spots) {
      this.byCell.set(this.index(s.x, s.y), s);
      this.byId.set(s.id, s);
      if (s.zoneId && !isPortalSpot(s)) this.byZone.set(s.zoneId, [...(this.byZone.get(s.zoneId) ?? []), s]);
    }
  }

  get size(): number {
    return this.width * this.height;
  }
  // Индекс клетки в массивах карты. Клетка вне карты даёт чужой индекс — сначала inBounds.
  index(x: number, y: number): number {
    return (y - this.originY) * this.width + (x - this.originX);
  }
  cell(i: number): [number, number] {
    return [(i % this.width) + this.originX, Math.floor(i / this.width) + this.originY];
  }
  inBounds(x: number, y: number): boolean {
    return x >= this.originX && y >= this.originY && x < this.originX + this.width && y < this.originY + this.height;
  }
  isBlocked(x: number, y: number): boolean {
    return !this.inBounds(x, y) || this.blocked[this.index(x, y)] === 1;
  }
  // Цена шага в клетку (спека маршрутов 3.2): здание — 1, участок — walk земли или декали.
  cost(x: number, y: number): number {
    return this.costs?.[this.index(x, y)] ?? 1;
  }
  isHidden(x: number, y: number): boolean {
    return this.inBounds(x, y) && this.hidden.has(this.index(x, y));
  }
  // Тип земли клетки участка; клетки здания и карта без участка — null.
  terrainAt(x: number, y: number): string | null {
    return this.inBounds(x, y) ? (this.terrain?.[this.index(x, y)] ?? null) : null;
  }
  spotAt(x: number, y: number): Spot | undefined {
    return this.inBounds(x, y) ? this.byCell.get(this.index(x, y)) : undefined;
  }
  spot(id: string): Spot | undefined {
    return this.byId.get(id);
  }
  spotsInZone(zoneId: string): Spot[] {
    return this.byZone.get(zoneId) ?? [];
  }
  spotPoint(s: Spot): [number, number] {
    return spotPoint(s, this.tileSize);
  }
  dock(spotId: string): DockSpot | undefined {
    return this.byDock.get(spotId);
  }
  // Клетка капсулы или тумбы.
  inDockBody(x: number, y: number): boolean {
    return this.dockAt(x, y) !== undefined;
  }
  // Капсула, которой принадлежит клетка капсулы или тумбы.
  dockAt(x: number, y: number): DockSpot | undefined {
    return this.inBounds(x, y) ? this.dockBody.get(this.index(x, y)) : undefined;
  }
  // Клетка капсулы, тумбы или пола перед капсулой.
  inDockArea(x: number, y: number): boolean {
    return this.inBounds(x, y) && this.dockArea.has(this.index(x, y));
  }
  // Транзит — пол без блокирующих предметов и без мест (спека 5.4).
  isTransit(x: number, y: number): boolean {
    return !this.isBlocked(x, y) && this.spotAt(x, y) === undefined;
  }
  entrance(): [number, number] {
    const e = this.entrances[0];
    if (!e) throw new Error('у карты нет входа');
    return e;
  }
}

type Placed = { uid: string; item: string; x: number; y: number; facing: Facing | null; variant: number; tags: string[] };

export function buildWorldMap(layout: OfficeLayout, catalog: Catalog, file = 'office.yaml'): Result<WorldMap> {
  const site = layout.site;
  // Карта ходьбы (спека маршрутов 4.1): без участка — здание, с участком — весь site.rect; клетки мировые.
  const [ox, oy, W, H] = site ? site.rect : [0, 0, layout.width, layout.height];
  const idx = (x: number, y: number) => (y - oy) * W + (x - ox);
  const errors: MapError[] = [];
  const blocked = new Uint8Array(W * H);
  const cost = new Uint8Array(W * H).fill(1);
  const terrain = new Array<string | null>(W * H).fill(null);
  const hidden: [number, number][] = [];
  const entrances: [number, number][] = [];
  layout.base.forEach((k, i) => {
    const x = i % layout.width;
    const y = Math.floor(i / layout.width);
    if (k === 'wall') blocked[idx(x, y)] = 1;
    if (k === 'entrance') entrances.push([x, y]);
  });
  const e = entrances[0];
  if (site) {
    for (let i = 0; i < W * H; i++) {
      const x = (i % W) + ox;
      const y = Math.floor(i / W) + oy;
      const t = site.terrain[i]!;
      if (t === BUILDING) {
        if (y < layout.height) continue; // клетки здания — по сетке здания
        // Два ряда фасада: проходим только столбец E — проход сквозь дверь виден, скрытых клеток здесь нет (спека двери 4.2).
        if (!e || x !== e[0]) blocked[i] = 1;
        continue;
      }
      terrain[i] = t;
      const walk = catalog.terrains[t]?.walk ?? null;
      if (walk === null) blocked[i] = 1;
      else cost[i] = walk;
    }
    // Декаль со своим walk заменяет цену земли под ней: так дорогу переходят по зебре (спека маршрутов 3.2).
    for (const it of site.items) {
      const def = catalog.items[it.item]!;
      if (def.layer !== 'ground' || def.walk === null) continue;
      blocked[idx(it.x, it.y)] = 0;
      cost[idx(it.x, it.y)] = def.walk;
    }
  }
  const placed: Placed[] = [...layout.items, ...(site?.items ?? [])];
  for (const it of placed) for (const [dx, dy] of catalog.items[it.item]!.blocks) blocked[idx(it.x + dx, it.y + dy)] = 1;
  const spots: Spot[] = [];
  const taken = new Map<number, string>();
  for (const it of placed) {
    const view = itemView(catalog.items[it.item]!, it.facing, it.variant);
    view.spots.forEach((s, i) => {
      const x = it.x + s.cell[0];
      const y = it.y + s.cell[1];
      const k = idx(x, y);
      const id = `${it.uid}#${i}`;
      if (blocked[k]) return errors.push({ file, code: 'spot_blocked', message: `место ${id} на блокирующей клетке`, at: [x, y] });
      const other = taken.get(k);
      if (other) return errors.push({ file, code: 'spot_duplicate', message: `места ${other} и ${id} в одной клетке`, at: [x, y] });
      taken.set(k, id);
      spots.push({
        id,
        x,
        y,
        facing: s.facing ?? it.facing ?? 'down',
        pose: s.pose,
        offset: s.offset,
        label: s.label,
        fidgets: s.fidgets,
        tags: [...new Set([...s.tags, ...catalog.items[it.item]!.tags, ...it.tags])], // спека 5.1: теги каталога + теги предмета
        itemUid: it.uid,
        zoneId: zoneAt(layout.zones, x, y)?.id ?? null,
      });
    });
  }
  let metro: [number, number] | null = null;
  if (site) {
    // Спуск в метро — предмет участка с portal; на участке он ровно один (спека маршрутов 3.4, 3.8).
    const metros = site.items.filter((it) => catalog.items[it.item]!.portal);
    if (metros.length === 0) errors.push({ file, code: 'site_no_metro', message: 'на участке нет спуска в метро (предмет с portal, metro_entrance)' });
    if (metros.length > 1) errors.push({ file, code: 'site_metro_multiple', message: `спусков в метро на участке ${metros.length}, нужен один`, at: [metros[1]!.x, metros[1]!.y] });
    const m = metros[0];
    if (m) {
      const p = catalog.items[m.item]!.portal!;
      metro = [m.x + p.cell[0], m.y + p.cell[1]];
      for (const [dx, dy] of p.hidden) hidden.push([m.x + dx, m.y + dy]);
    }
  }
  // Транспорт участка (спека транспорта 4.1): места, карман и маршруты считаются и проверяются при загрузке.
  let transport: TransportPlan | null = null;
  if (site) {
    const t = buildTransport({ site, catalog, spotCells: new Set(spots.map((s) => `${s.x},${s.y}`)), busStop: spots.some((s) => s.tags.includes('bus_wait')), file });
    if (t.ok) transport = t.value;
    else errors.push(...t.errors);
  }
  // Портал агентов (спека маршрутов 4.3): metro требует спуска на участке — на любом участке он есть, без участка его нет.
  const agentArrival = layout.agents?.arrival ?? 'dock';
  if (agentArrival === 'metro' && !metro) errors.push({ file, code: 'agents_arrival_metro', message: 'agents.arrival: metro — а спуска в метро на участке нет (нужен site с metro_entrance)' });
  if (errors.length) return fail(errors);
  const spotById = new Map(spots.map((s) => [s.id, s]));
  const ts = catalog.tileSize;
  const docks: DockSpot[] = [];
  for (const it of placed) {
    for (const c of catalog.items[it.item]!.dock?.capsules ?? []) {
      const s = spotById.get(`${it.uid}#${c.spot}`);
      if (!s) continue; // место капсулы на блоке — ошибку уже дала проверка мест
      const w = ([dx, dy]: [number, number]): [number, number] => [it.x + dx, it.y + dy];
      const plinth = c.plinth.map(w);
      const bottom = Math.max(...plinth.map(([, y]) => y));
      const cols = [...new Set(plinth.map(([x]) => x))].sort((a, b) => a - b);
      docks.push({
        spotId: s.id,
        point: spotPoint(s, ts),
        cells: c.cells.map(w),
        plinth,
        front: cols.map((x): [number, number] => [x, bottom + 1]),
        item: { id: it.item, uid: it.uid, x: it.x, y: it.y },
        at: c.at,
      });
    }
  }
  const siteUids = new Set((site?.items ?? []).map((it) => it.uid));
  // Точка у двери: при участке — второй ряд тротуара под проёмом (точка появления этапа 1), иначе — сам вход.
  const doorPoint: [number, number] | undefined = site && e && e[1] === layout.height - 1 ? [e[0], layout.height + 3] : e;
  return ok(
    new WorldMap({
      originX: ox,
      originY: oy,
      width: W,
      height: H,
      blocked,
      cost,
      ...(site ? { terrain } : {}),
      hidden,
      spots,
      zones: layout.zones,
      entrances,
      ...(doorPoint ? { doorPoint } : {}),
      site: !!site,
      tileSize: ts,
      transport,
      agentArrival,
      portals: {
        metro,
        carSpots: transport ? transport.spots.map((s) => s.cell) : [],
        // Спят только на скамейках участка (спека сна 5.1): боковая скамейка в здании — декорация, её место — портал,
        // правила его не выбирают, а без участка спальных мест нет и человек парка ездит на метро.
        parkSleep: spots.filter((s) => s.tags.includes('park_sleep') && siteUids.has(s.itemUid)).map((s) => s.id),
        docks,
      },
    }),
  );
}
