import { buildWorldMap, loadCatalog, ok, parseOffice, parseYamlWith, type OfficeLayout, type Result, type WorldMap } from '@pixeloffice/core';
import { z } from 'zod';

// Минимальная схема office.yaml: только сетки и легенды — для символов карты в join (спека арены 6.1).
// Полную проверку делает parseOffice; здесь извлекаем только то, чего нет в OfficeLayout, — сырые символы.
// Объектные ветки — по образцу LegendValue/SiteLegendValue из core (office.ts, site.ts): у реальных легенд
// бывают facing/variant/on/tags, и одна строгая ветка без них отвергает offices/local целиком (facing у кресел,
// on у маркеров участка).
const LegendValue = z.union([
  z.string(),
  z.strictObject({ item: z.string(), on: z.string().optional(), facing: z.string().optional(), variant: z.number().int().optional(), tags: z.array(z.string()).optional() }),
  z.strictObject({ terrain: z.string(), tags: z.array(z.string()).optional() }),
  z.strictObject({ marker: z.string(), on: z.string().optional(), facing: z.string().optional() }),
]);
const OfficeGrids = z.object({
  grid: z.string().min(1),
  legend: z.record(z.string().length(1), LegendValue),
  site: z.object({ grid: z.string().min(1), legend: z.record(z.string().length(1), LegendValue) }).optional(),
});

// Значение легенды ответа — строка (решение плана 7): маркеры с префиксом, декали — id предмета.
const legendText = (v: z.infer<typeof LegendValue>): string =>
  typeof v === 'string' ? v : 'item' in v ? v.item : 'terrain' in v ? v.terrain : `marker:${v.marker}`;

export type ArenaMap = {
  map: WorldMap;
  origin: [number, number];
  size: [number, number];
  building: [number, number, number, number];
  cells: string[][];
  walkable: number[][];
  legend: Record<string, string>;
  siteLegend: Record<string, string> | undefined;
  isWall: (x: number, y: number) => boolean;
};

const rows = (grid: string): string[] => grid.replace(/\r/g, '').replace(/\n+$/, '').split('\n');

// Арена из офиса: каталог + office.yaml → карта ходьбы core + символы для клиента (спека арены 3.4).
// rules/people/config не читаем, loadOfficeBundle не зовём — он требует все файлы офиса.
export function buildArenaMap(officeText: string, catalogText: string): Result<ArenaMap> {
  const catalog = loadCatalog(catalogText);
  if (!catalog.ok) return catalog;
  const layout: Result<OfficeLayout> = parseOffice(officeText, catalog.value);
  if (!layout.ok) return layout;
  const map = buildWorldMap(layout.value, catalog.value);
  if (!map.ok) return map;
  const grids = parseYamlWith('office.yaml', officeText, OfficeGrids);
  if (!grids.ok) return grids;
  const l = layout.value;
  const m = map.value;
  const siteRows = grids.value.site ? rows(grids.value.site.grid) : [];
  const buildingRows = rows(grids.value.grid);

  // Символы: сетка здания на своём прямоугольнике, вокруг — сетка участка (спека арены 6.1).
  const cells: string[][] = [];
  const walkable: number[][] = [];
  for (let y = 0; y < m.height; y++) {
    const cellRow: string[] = [];
    const walkRow: number[] = [];
    for (let x = 0; x < m.width; x++) {
      const wx = m.originX + x;
      const wy = m.originY + y;
      const inBuilding = wx >= 0 && wy >= 0 && wx < l.width && wy < l.height;
      cellRow.push(inBuilding ? (buildingRows[wy]?.[wx] ?? ' ') : (siteRows[wy - m.originY]?.[wx - m.originX] ?? ' '));
      walkRow.push(m.isBlocked(wx, wy) ? 0 : 1);
    }
    cells.push(cellRow);
    walkable.push(walkRow);
  }

  // Стены для FOV — только стены здания из сетки office.yaml (спека арены 5.2): фасад, двери и мебель взгляд не блокируют.
  const isWall = (x: number, y: number): boolean =>
    x >= 0 && y >= 0 && x < l.width && y < l.height && l.base[y * l.width + x] === 'wall';

  return ok({
    map: m,
    origin: [m.originX, m.originY],
    size: [m.width, m.height],
    building: l.site ? l.site.building : [0, 0, l.width, l.height],
    cells,
    walkable,
    legend: Object.fromEntries(Object.entries(grids.value.legend).map(([k, v]) => [k, legendText(v)])),
    siteLegend: grids.value.site
      ? Object.fromEntries(Object.entries(grids.value.site.legend).map(([k, v]) => [k, legendText(v)]))
      : undefined,
    isWall,
  });
}
