import { z } from 'zod';
import { FacingSchema, type Facing } from '@pixeloffice/protocol';
import type { Catalog } from './catalog.ts';
import { fail, ok, type MapError, type Result } from './errors.ts';
import { checkFacing, checkVariant, scanItems, type ErrFn } from './grid.ts';

const Int = z.number().int();
const SiteLegendValue = z.union([
  z.string().min(1),
  z.strictObject({ terrain: z.string().min(1), tags: z.array(z.string()).optional() }),
  z.strictObject({
    item: z.string().min(1),
    on: z.string().optional(),
    facing: FacingSchema.optional(),
    variant: Int.min(1).optional(),
    tags: z.array(z.string()).optional(),
  }),
  z.strictObject({ marker: z.string().min(1), on: z.string().optional(), facing: FacingSchema.optional() }),
]);
// Секция site: office.yaml (спека 3.1): участок вокруг здания — своя сетка и легенда.
export const SiteFileSchema = z.strictObject({
  legend: z.record(z.string().length(1), SiteLegendValue),
  grid: z.string().min(1),
  fill: z.string().min(1).default('grass'), // земля под предметами и маркерами без on (спека 3.3)
  view: z.tuple([Int.min(0), Int.min(0), Int.positive(), Int.positive()]).optional(), // обязателен — проверяет parseSite
});
export type SiteFile = z.output<typeof SiteFileSchema>;

export const BUILDING = 'building';
export type CellRect = [number, number, number, number];
export type SiteItem = { uid: string; item: string; x: number; y: number; facing: Facing | null; variant: number; tags: string[] };
export type SiteMarker = { name: string; x: number; y: number; facing?: 'up' | 'down' }; // facing — у car_spot (спека транспорта 3.3)
export type SiteCellTags = { x: number; y: number; tags: string[] };
// Участок в мировых клетках (спека 3.3, 5.1): начало мира — левый верхний угол сетки здания, клетки левее и выше
// отрицательные. terrain — тип земли по клеткам сетки участка (индекс sy * ширина + sx), BUILDING — блок @.
// Маркеры и теги клеток — задел под этап 2, в RenderedMap не передаются (спека 5.4).
export type SiteLayout = {
  rect: CellRect;
  building: CellRect;
  view: CellRect;
  terrain: string[];
  items: SiteItem[];
  markers: SiteMarker[];
  tags: SiteCellTags[];
};

type Entry =
  | { kind: 'building' }
  | { kind: 'terrain'; terrain: string; tags: string[] }
  | { kind: 'item'; item: string; on: string; facing: Facing | null; variant: number; tags: string[] }
  | { kind: 'marker'; name: string; on: string; facing?: 'up' | 'down' };
type ItemSpec = { item: string; on?: string | undefined; facing?: Facing | undefined; variant?: number | undefined; tags?: string[] | undefined };

// Координаты в ошибках — клетки сетки участка (решение плана 8).
export function parseSite(s: SiteFile, building: { width: number; height: number }, catalog: Catalog, file = 'office.yaml'): Result<SiteLayout> {
  const errors: MapError[] = [];
  const err: ErrFn = (code, message, at) => errors.push(at ? { file, code, message, at } : { file, code, message });

  // Без фасада, двери и правил нижнего ряда стен участок не нарисовать (решение плана 1).
  if (!catalog.facade || !catalog.door || !catalog.items['wall']?.autotile?.site) err('site_catalog', 'site: в каталоге нужны facade, door и items.wall.autotile.site');

  // 1. Геометрия сетки.
  const rows = s.grid.replace(/\r/g, '').replace(/\n+$/, '').split('\n');
  // Ширина — самая частая длина строки (при равенстве — раньше встретившаяся): одна кривая строка даёт одну ошибку, а не по ошибке на каждую остальную.
  const lengths = new Map<number, number>();
  for (const r of rows) lengths.set(r.length, (lengths.get(r.length) ?? 0) + 1);
  let W = rows[0]?.length ?? 0;
  for (const [len, n] of lengths) if (n > lengths.get(W)!) W = len;
  const H = rows.length;
  let ragged = false;
  rows.forEach((r, y) => {
    if (r.length === W) return;
    ragged = true;
    err('site_ragged', `site: строка ${y} длиной ${r.length}, ожидалось ${W}`, [0, y]);
  });
  if (ragged) return fail(errors);

  // 2. Легенда: строка — building, тип земли или предмет — именно в таком порядке (спека 3.1).
  const isTerrain = (n: string) => Object.hasOwn(catalog.terrains, n);
  if (!isTerrain(s.fill)) err('site_unknown', `site.fill: типа земли «${s.fill}» нет в terrains`);
  const groundOf = (on: string | undefined, where: string): string => {
    if (on !== undefined && !isTerrain(on)) err('site_unknown', `${where}: on — типа земли «${on}» нет в terrains`);
    return on ?? s.fill;
  };
  const legend = new Map<string, Entry>();
  const addItem = (ch: string, where: string, spec: ItemSpec): void => {
    const def = catalog.items[spec.item];
    if (!def) return err('site_unknown', `${where}: предмета «${spec.item}» нет в каталоге`);
    // Дверь-предмет ставится только в проём внутренней стены здания (спека северных комнат 5.2).
    if (def.door) return err('door_not_in_wall', `${where}: дверь «${spec.item}» ставится только в проём внутренней стены здания, не на участок`);
    // Предмет крыши ставится только в roofs здания (спека крыш 4.2.6).
    if (def.roof) return err('roof_prop_placed', `${where}: предмет крыши «${spec.item}» ставится только в roofs здания`);
    const facing = checkFacing(def, spec.facing, where, err);
    const variant = spec.variant ?? 1;
    checkVariant(def, variant, where, err);
    legend.set(ch, { kind: 'item', item: spec.item, on: groundOf(spec.on, where), facing, variant, tags: spec.tags ?? [] });
  };
  for (const [ch, v] of Object.entries(s.legend)) {
    const where = `site.legend '${ch}'`;
    if (typeof v === 'string') {
      if (v === BUILDING) legend.set(ch, { kind: 'building' });
      else if (isTerrain(v)) legend.set(ch, { kind: 'terrain', terrain: v, tags: [] });
      else if (catalog.items[v]) addItem(ch, where, { item: v });
      else err('site_unknown', `${where}: «${v}» нет ни в terrains, ни в items`);
    } else if ('terrain' in v) {
      if (isTerrain(v.terrain)) legend.set(ch, { kind: 'terrain', terrain: v.terrain, tags: v.tags ?? [] });
      else err('site_unknown', `${where}: типа земли «${v.terrain}» нет в terrains`);
    } else if ('item' in v) addItem(ch, where, v);
    else {
      // facing — куда смотрит машина на месте (спека транспорта 3.3): только у car_spot и только up или down.
      if (v.facing !== undefined && (v.marker !== 'car_spot' || (v.facing !== 'up' && v.facing !== 'down')))
        err('marker_facing', `${where}: facing «${v.facing}» бывает только у car_spot и только up или down`);
      const facing = v.marker === 'car_spot' && (v.facing === 'up' || v.facing === 'down') ? v.facing : undefined;
      legend.set(ch, { kind: 'marker', name: v.marker, on: groundOf(v.on, where), ...(facing ? { facing } : {}) });
    }
  }

  // 3. Блок здания: один прямоугольник ширина × (высота + 2) — два нижних ряда под фасад (спека 3.2).
  // Рамка клеток building и их число — в одном проходе.
  let count = 0;
  let [bx, by, x1, y1] = [W, H, -1, -1];
  for (let y = 0; y < H; y++) {
    for (let x = 0; x < W; x++) {
      if (legend.get(rows[y]![x]!)?.kind !== 'building') continue;
      count++;
      bx = Math.min(bx, x);
      by = Math.min(by, y);
      x1 = Math.max(x1, x);
      y1 = Math.max(y1, y);
    }
  }
  if (count === 0) {
    err('site_building_missing', 'site: в сетке нет блока здания (building)');
    return fail(errors);
  }
  const bw = x1 - bx + 1;
  const bh = y1 - by + 1;
  if (count !== bw * bh) {
    err('site_building_multiple', 'site: клетки здания — не один прямоугольник', [bx, by]);
    return fail(errors);
  }
  if (bw !== building.width || bh !== building.height + 2)
    err('site_building_size', `site: блок здания ${bw}×${bh}, нужен ${building.width}×${building.height + 2} (здание и два ряда фасада)`, [bx, by]);

  // 4. Земля, теги клеток, маркеры. Мировые клетки = клетки участка − (bx, by).
  const terrain = new Array<string>(W * H).fill(s.fill);
  const tags: SiteCellTags[] = [];
  const markers: SiteMarker[] = [];
  for (let y = 0; y < H; y++) {
    for (let x = 0; x < W; x++) {
      const ch = rows[y]![x]!;
      const e = legend.get(ch);
      if (!e) {
        if (!(ch in s.legend)) err('site_unknown', `site: символа '${ch}' нет в legend`, [x, y]);
        continue;
      }
      const i = y * W + x;
      if (e.kind === 'building') terrain[i] = BUILDING;
      else if (e.kind === 'terrain') {
        terrain[i] = e.terrain;
        if (e.tags.length) tags.push({ x: x - bx, y: y - by, tags: [...e.tags] });
      } else {
        terrain[i] = e.on;
        if (e.kind === 'marker') markers.push({ name: e.name, x: x - bx, y: y - by, ...(e.facing ? { facing: e.facing } : {}) });
      }
    }
  }

  // 5. Предметы и декали: многоклеточный — прямоугольник size из повторённого символа (спека 3.1).
  const itemAt = (ch: string) => {
    const e = legend.get(ch);
    return e?.kind === 'item' ? e : null;
  };
  const items: SiteItem[] = [];
  for (const { fp, e } of scanItems(rows, itemAt, catalog)) {
    if (!fp.complete) {
      err('incomplete_footprint', `site: «${e.item}» ${fp.w}×${fp.h} с символа '${fp.ch}': неполный прямоугольник`, [fp.x, fp.y]);
      continue;
    }
    const x = fp.x - bx;
    const y = fp.y - by;
    items.push({ uid: `site:${e.item}@${x},${y}`, item: e.item, x, y, facing: e.facing, variant: e.variant, tags: [...e.tags] });
  }

  // 6. Кадр при старте — обязателен и внутри участка (спека 3.3).
  const v = s.view;
  if (!v) err('site_view', 'site.view: обязателен — кадр при старте в клетках участка');
  else if (v[0] + v[2] > W || v[1] + v[3] > H) err('site_view', `site.view [${v.join(', ')}] выходит за участок ${W}×${H}`, [v[0], v[1]]);
  if (errors.length || !v) return fail(errors);
  return ok({ rect: [-bx, -by, W, H], building: [0, 0, bw, bh], view: [v[0] - bx, v[1] - by, v[2], v[3]], terrain, items, markers, tags });
}
