import { z } from 'zod';
import { FacingSchema, type Facing } from '@pixeloffice/protocol';
import { faceParts, itemView, type Catalog } from './catalog.ts';
import { roofTileBox } from './render-roofs.ts';
import { fail, ok, type MapError, type Result } from './errors.ts';
import { checkFacing, checkVariant, scanItems, type ErrFn } from './grid.ts';
import { SiteFileSchema, parseSite, type SiteLayout } from './site.ts';
import { SignSchema, type SignConfig } from './sign.ts';
import { parseYamlWith } from './yaml.ts';

const Int = z.number().int();
const LegendValue = z.union([
  z.string(),
  z.strictObject({ item: z.string(), facing: FacingSchema.optional(), variant: Int.min(1).optional(), tags: z.array(z.string()).optional() }),
]);
const OfficeFileSchema = z.strictObject({
  size: z.tuple([Int.positive(), Int.positive()]).optional(),
  floor: z.strictObject({ default: z.string(), zones: z.record(z.string(), z.string()).default({}) }),
  // Стиль лиц стен по зонам (спека северных комнат 5.1), как floor; нет default — autotile.style каталога.
  walls: z.strictObject({ default: z.string().optional(), zones: z.record(z.string(), z.string()).default({}) }).optional(),
  legend: z.record(z.string().length(1), LegendValue),
  grid: z.string().min(1),
  placements: z
    .array(
      z.strictObject({
        item: z.string(),
        at: z.tuple([Int.min(0), Int.min(0)]),
        on: z.string().optional(),
        facing: FacingSchema.optional(),
        variant: Int.min(1).optional(),
        tags: z.array(z.string()).optional(),
      }),
    )
    .default([]),
  zones: z
    .array(z.strictObject({ id: z.string().min(1), kind: z.enum(['pod', 'meeting', 'common']), rect: z.tuple([Int.min(0), Int.min(0), Int.positive(), Int.positive()]) }))
    .default([]),
  // Крыши над комнатами (спека крыш 4.1): комната со стенами по периметру и предметы на крыше, клетки здания.
  roofs: z
    .array(
      z.strictObject({
        rect: z.tuple([Int.min(0), Int.min(0), Int.positive(), Int.positive()]),
        props: z.array(z.strictObject({ item: z.string(), at: z.tuple([Int.min(0), Int.min(0)]) })).default([]),
      }),
    )
    .default([]),
  site: SiteFileSchema.optional(),
  sign: SignSchema.optional(), // вывеска над входом (спека хостинга 3.1)
  // Агенты (спека маршрутов 4.3): портал появления и ухода; нет секции — как раньше (капсулы дока, нет капсул — дверь).
  agents: z.strictObject({ arrival: z.enum(['dock', 'metro', 'door']) }).optional(),
});

export type CellKind = 'floor' | 'wall' | 'entrance';
export type PlacedItem = {
  uid: string;
  item: string;
  x: number;
  y: number;
  facing: Facing | null;
  variant: number;
  tags: string[];
  on: string | null;
  origin: 'grid' | 'placement';
};
export type Zone = { id: string; kind: 'pod' | 'meeting' | 'common'; rect: [number, number, number, number] };
export type RoofProp = { item: string; x: number; y: number };
// Крыша над комнатой (спека крыш 4.1): rect — комната вместе со стенами по периметру, клетки здания; props — предметы
// крыши на клетках её внутренней части.
export type Roof = { rect: [number, number, number, number]; props: RoofProp[] };
export type OfficeLayout = {
  width: number;
  height: number;
  base: CellKind[];
  items: PlacedItem[];
  zones: Zone[];
  floor: { default: string; zones: Record<string, string> };
  walls: { default: string | null; zones: Record<string, string> }; // стили лиц стен; default null — у каталога без лиц face
  roofs: Roof[]; // крыши над комнатами (спека крыш 4); нет секции — []
  site?: SiteLayout; // участок вокруг здания (спека 3); нет — офис как раньше
  sign?: SignConfig; // вывеска из office.yaml; нет — undefined
  agents?: { arrival: 'dock' | 'metro' | 'door' }; // портал агентов (спека маршрутов 4.3); нет — капсулы или дверь
};

type LegendEntry =
  | { kind: CellKind }
  | { kind: 'item'; item: string; facing: Facing | null; variant: number; tags: string[] };

const KEYWORDS: Record<string, CellKind> = { wall: 'wall', floor: 'floor', entrance: 'entrance' };

export const zoneContains = (z: Zone, x: number, y: number) =>
  x >= z.rect[0] && y >= z.rect[1] && x < z.rect[0] + z.rect[2] && y < z.rect[1] + z.rect[3];
export const zoneAt = (zones: Zone[], x: number, y: number): Zone | null => zones.find((z) => zoneContains(z, x, y)) ?? null;

type CellRect = [number, number, number, number];
// Клетки прямоугольника построчно — слева направо, сверху вниз.
const rectCells = ([x, y, w, h]: CellRect): [number, number][] => Array.from({ length: w * h }, (_, i) => [x + (i % w), y + Math.floor(i / w)]);
const innerRect = ([x, y, w, h]: CellRect): CellRect => [x + 1, y + 1, w - 2, h - 2];
// Левая верхняя общая клетка двух прямоугольников; не пересекаются — null.
function rectMeet(a: CellRect, b: CellRect): [number, number] | null {
  const x0 = Math.max(a[0], b[0]);
  const y0 = Math.max(a[1], b[1]);
  const x1 = Math.min(a[0] + a[2], b[0] + b[2]);
  const y1 = Math.min(a[1] + a[3], b[1] + b[3]);
  return x0 < x1 && y0 < y1 ? [x0, y0] : null;
}

export function parseOffice(text: string, catalog: Catalog, file = 'office.yaml'): Result<OfficeLayout> {
  const parsed = parseYamlWith(file, text, OfficeFileSchema);
  if (!parsed.ok) return parsed;
  const f = parsed.value;
  const errors: MapError[] = [];
  const err: ErrFn = (code, message, at) => errors.push(at ? { file, code, message, at } : { file, code, message });

  // 1. Геометрия grid.
  const rows = f.grid.replace(/\r/g, '').replace(/\n+$/, '').split('\n');
  const width = rows[0]?.length ?? 0;
  const height = rows.length;
  rows.forEach((r, y) => {
    if (r.length !== width) err('grid_ragged', `строка ${y} длиной ${r.length}, ожидалось ${width}`, [0, y]);
  });
  if (f.size && (f.size[0] !== width || f.size[1] !== height)) err('size_mismatch', `size [${f.size.join(', ')}] не совпадает с grid ${width}×${height}`);
  if (errors.length) return fail(errors);
  const inBounds = (x: number, y: number) => x >= 0 && y >= 0 && x < width && y < height;

  // 2. Legend.
  const legend = new Map<string, LegendEntry>();
  for (const [ch, v] of Object.entries(f.legend)) {
    const spec = typeof v === 'string' ? { item: v } : v;
    const kw = KEYWORDS[spec.item];
    if (kw) {
      legend.set(ch, { kind: kw });
      continue;
    }
    const def = catalog.items[spec.item];
    if (!def) {
      err('unknown_item', `символ '${ch}': предмета «${spec.item}» нет в каталоге`);
      continue;
    }
    // Декаль (layer: ground) — разметка земли участка (спека 4.3): в здании она сортировалась бы со стенами и людьми.
    if (def.layer === 'ground') {
      err('ground_in_building', `символ '${ch}': декаль «${spec.item}» ставится только в сетку участка`);
      continue;
    }
    // Предмет крыши (спека крыш 4.2.6) ставится только в roofs: на полу у него нет ни карты, ни глубины.
    if (def.roof) {
      err('roof_prop_placed', `символ '${ch}': предмет крыши «${spec.item}» ставится только в roofs`);
      continue;
    }
    const facing = checkFacing(def, spec.facing, `символ '${ch}'`, err);
    const variant = 'variant' in spec && spec.variant ? spec.variant : 1;
    checkVariant(def, variant, `символ '${ch}'`, err);
    legend.set(ch, { kind: 'item', item: spec.item, facing, variant, tags: 'tags' in spec && spec.tags ? spec.tags : [] });
  }

  // 3. Клетки и жадный разбор footprint (спека 5.1).
  const base: CellKind[] = new Array<CellKind>(width * height).fill('floor');
  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      const ch = rows[y]![x]!;
      const e = legend.get(ch);
      if (!e) {
        if (!(ch in f.legend)) err('unknown_symbol', `символа '${ch}' нет в legend`, [x, y]);
      } else if (e.kind !== 'item') base[y * width + x] = e.kind;
    }
  }
  const itemAt = (ch: string) => {
    const e = legend.get(ch);
    return e?.kind === 'item' ? e : null;
  };
  const items: PlacedItem[] = [];
  for (const { fp, e } of scanItems(rows, itemAt, catalog)) {
    if (!fp.complete) {
      err('incomplete_footprint', `«${e.item}» ${fp.w}×${fp.h} с символа '${fp.ch}': неполный прямоугольник`, [fp.x, fp.y]);
      continue;
    }
    items.push({ uid: `${e.item}@${fp.x},${fp.y}`, item: e.item, x: fp.x, y: fp.y, facing: e.facing, variant: e.variant, tags: [...e.tags], on: null, origin: 'grid' });
  }

  // 4. Placements: аннотация или новый предмет.
  const covers = (it: PlacedItem, x: number, y: number) => {
    const [w, h] = catalog.items[it.item]!.size;
    return x >= it.x && y >= it.y && x < it.x + w && y < it.y + h;
  };
  f.placements.forEach((p, i) => {
    const where = `placements[${i}]`;
    const [x, y] = p.at;
    if (!inBounds(x, y)) return err('placement_out_of_bounds', `${where}: клетка вне карты`, [x, y]);
    const def = catalog.items[p.item];
    if (!def) return err('unknown_item', `${where}: предмета «${p.item}» нет в каталоге`, [x, y]);
    if (def.layer === 'ground') return err('ground_in_building', `${where}: декаль «${p.item}» ставится только в сетку участка`, [x, y]);
    if (def.roof) return err('roof_prop_placed', `${where}: предмет крыши «${p.item}» ставится только в roofs`, [x, y]);
    const existing = items.find((it) => it.origin === 'grid' && it.item === p.item && it.x === x && it.y === y);
    if (existing) {
      if (p.facing && p.facing !== existing.facing) err('annotation_facing', `${where}: аннотация меняет facing предмета из grid`, [x, y]);
      if (p.variant) {
        checkVariant(def, p.variant, where, err);
        existing.variant = p.variant;
      }
      if (p.tags) existing.tags.push(...p.tags);
      return;
    }
    const [w, h] = def.size;
    if (!inBounds(x + w - 1, y + h - 1)) return err('placement_out_of_bounds', `${where}: «${p.item}» ${w}×${h} не помещается в карту`, [x, y]);
    const facing = checkFacing(def, p.facing, where, err);
    const variant = p.variant ?? 1;
    checkVariant(def, variant, where, err);
    if (p.on && !items.some((it) => it.item === p.on && covers(it, x, y))) {
      err('on_target_missing', `${where}: под (${x},${y}) нет предмета «${p.on}»`, [x, y]);
    }
    items.push({ uid: `${p.item}@${x},${y}${p.on ? `^${p.on}` : ''}`, item: p.item, x, y, facing, variant, tags: p.tags ?? [], on: p.on ?? null, origin: 'placement' });
  });

  // 5. Пересечения блокирующих клеток (кроме предметов «на» других).
  const blockedBy = new Map<number, string>();
  for (const it of items) {
    if (it.on) continue;
    for (const [dx, dy] of catalog.items[it.item]!.blocks) {
      const cx = it.x + dx;
      const cy = it.y + dy;
      const idx = cy * width + cx;
      if (base[idx] !== 'floor') {
        err('overlap', `«${it.uid}» блокирует клетку стены или входа`, [cx, cy]);
        continue;
      }
      const other = blockedBy.get(idx);
      if (other) err('overlap', `«${it.uid}» и «${other}» блокируют одну клетку`, [cx, cy]);
      else blockedBy.set(idx, it.uid);
    }
  }

  // 5а. Двери-предметы (спека северных комнат 5.2): только в проёме внутренней горизонтальной стены — под дверью пол,
  // слева и справа стена, над и под каждой её клеткой не стена. Клетка за краем карты — стена, поэтому дверь во внешней
  // стене — ошибка. У двери blocks: none, и дверь из placements поверх «#» overlap не видит — её ловит эта проверка.
  const wallAt = (x: number, y: number) => !inBounds(x, y) || base[y * width + x] === 'wall';
  for (const it of items) {
    const def = catalog.items[it.item]!;
    if (!def.door) continue;
    const w = def.size[0];
    const cells = Array.from({ length: w }, (_, dx) => it.x + dx);
    const inGap =
      cells.every((x) => base[it.y * width + x] === 'floor' && !wallAt(x, it.y - 1) && !wallAt(x, it.y + 1)) && wallAt(it.x - 1, it.y) && wallAt(it.x + w, it.y);
    if (!inGap) err('door_not_in_wall', `«${it.uid}»: дверь ставится в проём внутренней горизонтальной стены — под ней пол, слева и справа стена, сверху и снизу не стена`, [it.x, it.y]);
  }

  // 5б. Крыши (спека крыш 4.2): комната со стенами по периметру — в южной стене, кроме углов, допустима дверь-предмет;
  // открытый проём и дверь в северной стене — нет (её крыша накрыла бы целиком). Внутренние части крыш не заходят на
  // чужие крыши, общие стены допустимы. Предметы крыши — предметы с roof: true на плитке крыши.
  if (f.roofs.length && !catalog.roof) err('roof_catalog', 'roofs: в каталоге нет раздела roof — крыши не нарисовать');
  const doorAt = (x: number, y: number) =>
    items.some((it) => {
      const d = catalog.items[it.item]!;
      return d.door !== null && y === it.y && x >= it.x && x < it.x + d.size[0];
    });
  const roofs: Roof[] = [];
  const ts = catalog.tileSize;
  f.roofs.forEach((r, i) => {
    const where = `roofs[${i}]`;
    const [x, y, w, h] = r.rect;
    if (!inBounds(x, y) || !inBounds(x + w - 1, y + h - 1)) return err('roof_out_of_bounds', `${where}: [${r.rect.join(', ')}] выходит за здание ${width}×${height}`, [x, y]);
    if (w < 3 || h < 3) return err('roof_too_small', `${where}: ${w}×${h} — нужно не меньше 3×3, иначе у крыши нет внутренней части`, [x, y]);
    const south = y + h - 1;
    const open = rectCells(r.rect).find(([cx, cy]) => {
      const edge = cy === y || cy === south || cx === x || cx === x + w - 1;
      if (!edge || wallAt(cx, cy)) return false;
      return !(cy === south && cx > x && cx < x + w - 1 && doorAt(cx, cy));
    });
    if (open) err('roof_not_walled', `${where}: клетка периметра — не стена (дверь-предмет допустима только в южной стене, открытый проём — нет)`, open);
    // Крыша нарисована на тайл выше своих клеток (спека крыш 4.4), а предмет — по клеткам: предмет проверяется в
    // пикселях — каждая часть кадра 0 лежит на плитке крыши (roofBox без рамки). Без раздела roof — уже roof_catalog.
    const tile = catalog.roof ? roofTileBox(r.rect, catalog.roof.border, ts) : null;
    const props: RoofProp[] = [];
    r.props.forEach((p, j) => {
      const pw = `${where}.props[${j}]`;
      const [px, py] = p.at;
      const def = catalog.items[p.item];
      if (!def) return err('unknown_item', `${pw}: предмета «${p.item}» нет в каталоге`, [px, py]);
      if (!def.roof) return err('not_roof_prop', `${pw}: «${p.item}» — не предмет крыши (нужен roof: true в каталоге)`, [px, py]);
      const outside =
        tile !== null &&
        itemView(def, null, 1).parts.some(({ rect: [, , rw, rh], at: [ax, ay] }) => {
          const [x0, y0] = [px * ts + ax, py * ts + ay];
          return x0 < tile.x0 || y0 < tile.y0 || x0 + rw > tile.x1 || y0 + rh > tile.y1;
        });
      if (outside) return err('roof_prop_outside', `${pw}: «${p.item}» вылезает за плитку крыши (px x ${tile.x0}…${tile.x1}, y ${tile.y0}…${tile.y1})`, [px, py]);
      props.push({ item: p.item, x: px, y: py });
    });
    roofs.push({ rect: r.rect, props });
  });
  roofs.forEach((a, i) => {
    for (const b of roofs.slice(i + 1)) {
      const at = rectMeet(innerRect(a.rect), b.rect) ?? rectMeet(innerRect(b.rect), a.rect);
      if (at) err('roof_overlap', `крыши [${a.rect.join(', ')}] и [${b.rect.join(', ')}] пересекаются не только по общей стене`, at);
    }
  });

  // 6. Зоны и пол.
  const zoneIds = new Set<string>();
  for (const z of f.zones) {
    if (zoneIds.has(z.id)) err('zone_duplicate', `зона «${z.id}» описана дважды`);
    zoneIds.add(z.id);
    const [x, y, w, h] = z.rect;
    if (!inBounds(x, y) || !inBounds(x + w - 1, y + h - 1)) err('zone_out_of_bounds', `зона «${z.id}» выходит за карту`, [x, y]);
  }
  // Место относится к первой подходящей зоне (zoneAt): перекрытие молча увело бы места в чужую зону.
  f.zones.forEach((a, i) => {
    for (const b of f.zones.slice(i + 1)) {
      const x0 = Math.max(a.rect[0], b.rect[0]);
      const y0 = Math.max(a.rect[1], b.rect[1]);
      const x1 = Math.min(a.rect[0] + a.rect[2], b.rect[0] + b.rect[2]);
      const y1 = Math.min(a.rect[1] + a.rect[3], b.rect[1] + b.rect[3]);
      if (x0 < x1 && y0 < y1) err('zone_overlap', `зоны «${a.id}» и «${b.id}» пересекаются`, [x0, y0]);
    }
  });
  if (!catalog.floors[f.floor.default]) err('unknown_floor', `floor.default: типа пола «${f.floor.default}» нет в каталоге`);
  for (const [zid, type] of Object.entries(f.floor.zones)) {
    if (!zoneIds.has(zid)) err('unknown_zone', `floor.zones: зоны «${zid}» нет в zones`);
    if (!catalog.floors[type]) err('unknown_floor', `floor.zones.${zid}: типа пола «${type}» нет в каталоге`);
  }

  // Стили стен (спека северных комнат 5.1): по умолчанию — walls.default, иначе autotile.style каталога, иначе null
  // (каталог без частей face — стиль не нужен).
  const wallAuto = catalog.items['wall']!.autotile!;
  const walls = { default: f.walls?.default ?? wallAuto.style ?? null, zones: f.walls?.zones ?? {} };
  if (f.walls) {
    if (faceParts(wallAuto).length === 0) err('walls_unused', 'walls: в правилах автотайла стены нет частей face — стили ни на что не влияют');
    const known = (s: string) => Object.hasOwn(catalog.wallStyles, s);
    if (f.walls.default !== undefined && !known(f.walls.default)) err('unknown_wall_style', `walls.default: стиля стен «${f.walls.default}» нет в wallStyles`);
    for (const [zid, s] of Object.entries(f.walls.zones)) {
      if (!zoneIds.has(zid)) err('unknown_zone', `walls.zones: зоны «${zid}» нет в zones`);
      if (!known(s)) err('unknown_wall_style', `walls.zones.${zid}: стиля стен «${s}» нет в wallStyles`);
    }
  }

  // 7. Участок вокруг здания (спека 3).
  let site: SiteLayout | undefined;
  if (f.site) {
    const r = parseSite(f.site, { width, height }, catalog, file);
    if (r.ok) site = r.value;
    else errors.push(...r.errors);
  }
  if (errors.length) return fail(errors);
  return ok({ width, height, base, items, zones: f.zones, floor: f.floor, walls, roofs, ...(site ? { site } : {}), ...(f.sign ? { sign: f.sign } : {}), ...(f.agents ? { agents: f.agents } : {}) });
}
