import { describe, expect, it } from 'vitest';
import { loadCatalog, parseOffice, scanFootprints, zoneAt } from '../src/index.ts';
import { DOOR_ITEM, ROOF_CATALOG, ROOF_OFFICE, ROOF_VENT_ITEM, ROOMS_OFFICE, SITE_CATALOG, SITE_OFFICE, WORLD_OFFICE, miniCatalog, mutateYaml, office, roomsOffice, siteCatalog, roofCatalog, styledCatalog, tinyOffice } from './fixtures.ts';

const errs = (text: string) => {
  const r = parseOffice(text, miniCatalog());
  return r.ok ? [] : r.errors;
};
const codes = (text: string) => errs(text).map((e) => e.code);

describe('parseOffice', () => {
  it('разбирает офис: размеры, стены, вход, предметы', () => {
    const o = office();
    expect([o.width, o.height]).toEqual([14, 7]);
    expect(o.base[0]).toBe('wall');
    expect(o.base[6 * 14 + 6]).toBe('entrance');
    const desks = o.items.filter((i) => i.item === 'desk').map((i) => [i.x, i.y]);
    expect(desks).toEqual([[1, 1], [3, 1], [10, 1]]); // DDDD → два стола 2×1
    const owner = o.items.find((i) => i.item === 'chair' && i.x === 1 && i.y === 2)!;
    expect(owner.tags).toEqual(['owner_seat']); // аннотация, второго кресла нет
    expect(o.items.filter((i) => i.item === 'chair' && i.x === 1 && i.y === 2)).toHaveLength(1);
    const monitor = o.items.find((i) => i.item === 'monitor')!;
    expect(monitor).toMatchObject({ x: 1, y: 1, on: 'desk', origin: 'placement', uid: 'monitor@1,1^desk' });
    expect(o.items.filter((i) => i.item === 'arcade').map((i) => [i.x, i.y])).toEqual([[1, 4], [3, 4]]);
  });

  it('zoneAt находит зону клетки', () => {
    const o = office();
    expect(zoneAt(o.zones, 2, 2)?.id).toBe('pod:a');
    expect(zoneAt(o.zones, 8, 3)).toBeNull();
  });

  it('id зоны с двоеточием работает в floor.zones и zoneAt', () => {
    const text = mutateYaml(WORLD_OFFICE, (d) => (d.floor.zones = { 'pod:a': 'wood', 'meeting:m1': 'wood' }));
    const o = office(text);
    expect(o.floor.zones).toEqual({ 'pod:a': 'wood', 'meeting:m1': 'wood' });
    expect(zoneAt(o.zones, 6, 1)?.id).toBe('meeting:m1');
  });

  it('неполный footprint — ошибка с координатами', () => {
    const e = errs(tinyOffice(['####', '#D.#', '#E##'], { D: 'desk' }));
    expect(e.map((x) => x.code)).toContain('incomplete_footprint');
    expect(e.find((x) => x.code === 'incomplete_footprint')!.at).toEqual([1, 1]);
  });

  it('неполный вертикальный footprint (аркада 1×2 в одну строку)', () => {
    expect(codes(tinyOffice(['#####', '#.p.#', '#...#', '#E###'], { p: 'arcade' }))).toContain('incomplete_footprint');
  });

  it('строки grid разной длины', () => {
    expect(codes(tinyOffice(['####', '#..', '#E##'], {}))).toContain('grid_ragged');
  });

  it('size не совпадает с grid', () => {
    expect(codes(mutateYaml(WORLD_OFFICE, (d) => (d.size = [15, 7])))).toEqual(['size_mismatch']);
  });

  it('символа нет в legend — ошибка с координатами', () => {
    const e = errs(tinyOffice(['####', '#.x#', '#E##'], {}));
    expect(e).toEqual([expect.objectContaining({ code: 'unknown_symbol', at: [2, 1] })]);
  });

  it('предмет с направлениями без facing', () => {
    expect(codes(tinyOffice(['####', '#c.#', '#E##'], { c: 'chair' }))).toContain('facing_required');
  });

  it('неизвестный предмет', () => {
    expect(codes(tinyOffice(['####', '#z.#', '#E##'], { z: 'piano' }))).toContain('unknown_item');
  });

  it('placement «на» несуществующем предмете', () => {
    const text = mutateYaml(WORLD_OFFICE, (d) => d.placements.push({ item: 'monitor', at: [8, 3], on: 'desk' }));
    expect(codes(text)).toContain('on_target_missing');
  });

  it('новый предмет без on пересекает блокирующую клетку', () => {
    const text = mutateYaml(WORLD_OFFICE, (d) => d.placements.push({ item: 'plant', at: [2, 1] }));
    expect(codes(text)).toContain('overlap');
  });

  it('зона за пределами карты', () => {
    const text = mutateYaml(WORLD_OFFICE, (d) => d.zones.push({ id: 'far', kind: 'common', rect: [12, 5, 4, 4] }));
    expect(codes(text)).toContain('zone_out_of_bounds');
  });

  it('пересечение зон — ошибка zone_overlap с первой общей клеткой', () => {
    const text = mutateYaml(WORLD_OFFICE, (d) => d.zones.push({ id: 'bar', kind: 'common', rect: [3, 4, 2, 2] }));
    const r = parseOffice(text, miniCatalog());
    expect(r.ok ? [] : r.errors).toEqual([expect.objectContaining({ code: 'zone_overlap', at: [3, 4] })]);
  });

  it('пол: неизвестная зона и неизвестный тип пола', () => {
    const text = mutateYaml(WORLD_OFFICE, (d) => (d.floor.zones = { nowhere: 'wood', lounge: 'marble' }));
    expect(codes(text).sort()).toEqual(['unknown_floor', 'unknown_zone']);
  });

  it('декаль (layer: ground) в сетке здания и в placements — ground_in_building', () => {
    const siteErrs = (text: string) => {
      const r = parseOffice(text, siteCatalog());
      return r.ok ? [] : r.errors.map((e) => [e.code, e.at]);
    };
    expect(siteErrs(tinyOffice(['####', '#:.#', '#E##'], { ':': 'lane_dash' }))).toEqual([['ground_in_building', undefined]]);
    expect(siteErrs(mutateYaml(WORLD_OFFICE, (d) => d.placements.push({ item: 'lane_dash', at: [8, 3] })))).toEqual([['ground_in_building', [8, 3]]]);
  });

  it('собирает все ошибки сразу', () => {
    expect(errs(tinyOffice(['#####', '#x.y#', '#E###'], {})).length).toBe(2);
  });
});

describe('scanFootprints', () => {
  it('жадно слева направо, сверху вниз; неполный прямоугольник занимает только первую клетку', () => {
    const size = (ch: string): [number, number] | null => (ch === 'T' ? [2, 2] : null);
    expect(scanFootprints(['TTT.', 'TT..'], size)).toEqual([
      { ch: 'T', x: 0, y: 0, w: 2, h: 2, complete: true },
      { ch: 'T', x: 2, y: 0, w: 2, h: 2, complete: false },
    ]);
    expect(scanFootprints(['..'], size)).toEqual([]);
  });
});

describe('стили стен в office.yaml (спека северных комнат 5.1)', () => {
  const styledCodes = (text: string) => {
    const r = parseOffice(text, styledCatalog());
    return r.ok ? [] : r.errors.map((e) => e.code);
  };

  it('default — из autotile.style каталога, zones — из office.yaml', () => {
    expect(roomsOffice().walls).toEqual({ default: 'office', zones: { north: 'stone' } });
  });

  it('walls.default из office.yaml важнее стиля каталога', () => {
    expect(roomsOffice(mutateYaml(ROOMS_OFFICE, (d) => (d.walls.default = 'stone'))).walls.default).toBe('stone');
  });

  it('каталог без стиля и офис без walls — default null', () => {
    expect(office().walls).toEqual({ default: null, zones: {} });
  });

  it('ошибки: unknown_wall_style, unknown_zone, walls_unused', () => {
    expect(styledCodes(mutateYaml(ROOMS_OFFICE, (d) => (d.walls.default = 'nope')))).toEqual(['unknown_wall_style']);
    expect(styledCodes(mutateYaml(ROOMS_OFFICE, (d) => (d.walls.zones.north = 'nope')))).toEqual(['unknown_wall_style']);
    expect(styledCodes(mutateYaml(ROOMS_OFFICE, (d) => (d.walls.zones.ghost = 'stone')))).toEqual(['unknown_zone']);
    expect(codes(mutateYaml(WORLD_OFFICE, (d) => (d.walls = { zones: {} })))).toEqual(['walls_unused']); // в мини-каталоге нет частей face
  });
});

describe('door_not_in_wall (спека северных комнат 5.2)', () => {
  const styledCodes = (text: string) => {
    const r = parseOffice(text, styledCatalog());
    return r.ok ? [] : r.errors.map((e) => e.code);
  };
  // ROOMS_OFFICE с заменой рядов сетки и правкой документа.
  const withRows = (rows: Record<number, string>, edit: (d: any) => void = () => {}) =>
    mutateYaml(ROOMS_OFFICE, (d) => {
      const g = d.grid.replace(/\n$/, '').split('\n');
      for (const [i, row] of Object.entries(rows)) g[Number(i)] = row;
      d.grid = g.join('\n') + '\n';
      edit(d);
    });

  it('дверь в проёме внутренней горизонтальной стены — без ошибок', () => {
    expect(styledCodes(ROOMS_OFFICE)).toEqual([]);
  });

  it('не в стене: слева от двери пол', () => {
    expect(styledCodes(withRows({ 3: '##..######', 4: '#.GG.....#' }))).toEqual(['door_not_in_wall']);
  });

  // В двух проверках ниже нарушено одно условие: клетки двери — пол, по бокам стены, стена только над или только под
  // одной клеткой двери (G стоит в (2, 3)–(3, 3)).
  it('в вертикальной стене: над клеткой двери стена', () => {
    expect(styledCodes(withRows({ 2: '#..##....#' }))).toEqual(['door_not_in_wall']); // (3, 2) над (3, 3)
  });

  it('под клеткой двери стена', () => {
    expect(styledCodes(withRows({ 4: '#..#.....#' }))).toEqual(['door_not_in_wall']); // (3, 4) под (3, 3)
  });

  it('у края проёма пол', () => {
    expect(styledCodes(withRows({ 3: '#.GG######' }))).toEqual(['door_not_in_wall']);
  });

  it('из placements поверх «#»: overlap молчит (blocks: none), ловит door_not_in_wall', () => {
    expect(styledCodes(withRows({ 3: '##########' }, (d) => (d.placements = [{ item: 'elevator_door', at: [2, 3] }])))).toEqual(['door_not_in_wall']);
  });

  it('во внешней стене: клетка за краем карты — стена', () => {
    expect(styledCodes(withRows({ 0: '##GG######' }))).toEqual(['door_not_in_wall']);
  });

  it('на участке — та же ошибка', () => {
    const cat = loadCatalog(mutateYaml(SITE_CATALOG, (d) => (d.items.elevator_door = DOOR_ITEM)));
    if (!cat.ok) throw new Error(JSON.stringify(cat.errors));
    const r = parseOffice(mutateYaml(SITE_OFFICE, (d) => (d.site.legend.G = { item: 'elevator_door', on: 'sidewalk' })), cat.value);
    expect(r.ok ? [] : r.errors.map((e) => e.code)).toEqual(['door_not_in_wall']);
  });
});

describe('крыши roofs (спека крыш 4.1, 4.2)', () => {
  const roofErrs = (text: string) => {
    const r = parseOffice(text, roofCatalog());
    return r.ok ? [] : r.errors.map((e) => [e.code, e.at]);
  };
  const withRoofs = (roofs: unknown[], edit: (d: any) => void = () => {}) =>
    mutateYaml(ROOMS_OFFICE, (d) => {
      d.roofs = roofs;
      edit(d);
    });
  const row = (i: number, text: string) => (d: any) => {
    const g = d.grid.replace(/\n$/, '').split('\n');
    g[i] = text;
    d.grid = g.join('\n') + '\n';
  };

  it('разбор: rect и предметы клетками здания; без секции — пусто', () => {
    const r = parseOffice(ROOF_OFFICE, roofCatalog());
    if (!r.ok) throw new Error(JSON.stringify(r.errors));
    expect(r.value.roofs).toEqual([{ rect: [0, 0, 5, 4], props: [{ item: 'roof_vent', x: 1, y: 1 }] }]);
    expect(roomsOffice().roofs).toEqual([]);
  });

  it('две крыши с общей стеной — без ошибок; дверь в южной стене допустима', () => {
    expect(roofErrs(withRoofs([{ rect: [0, 0, 5, 4] }, { rect: [4, 0, 6, 4] }]))).toEqual([]);
  });

  it('roof_not_walled: клетка периметра — пол зала; открытый проём; дверь в северной стене', () => {
    expect(roofErrs(withRoofs([{ rect: [0, 0, 5, 5] }]))).toEqual([['roof_not_walled', [1, 4]]]);
    expect(roofErrs(withRoofs([{ rect: [0, 0, 5, 4] }], row(3, '##..######')))).toEqual([['roof_not_walled', [2, 3]]]);
    expect(roofErrs(withRoofs([{ rect: [0, 3, 5, 4] }]))).toEqual([['roof_not_walled', [2, 3]]]); // первая — дверь на севере
  });

  it('roof_overlap: внутренняя часть одной крыши на другой — место первой общей клетки', () => {
    expect(roofErrs(withRoofs([{ rect: [0, 0, 5, 4] }, { rect: [0, 0, 5, 4] }]))).toEqual([['roof_overlap', [1, 1]]]);
    // Крыша над обеими комнатами (стены периметра x 0–9, ряды 0–3) и крыша комнаты east: внутренняя часть большой
    // задевает западную стену east (4, 1), внутренняя часть east — большую крышу (5, 1).
    expect(roofErrs(withRoofs([{ rect: [0, 0, 10, 4] }, { rect: [4, 0, 6, 4] }]))).toEqual([['roof_overlap', [4, 1]]]);
    expect(roofErrs(withRoofs([{ rect: [4, 0, 6, 4] }, { rect: [0, 0, 10, 4] }]))).toEqual([['roof_overlap', [5, 1]]]);
  });

  it('roof_out_of_bounds и roof_too_small', () => {
    expect(roofErrs(withRoofs([{ rect: [6, 0, 5, 4] }]))).toEqual([['roof_out_of_bounds', [6, 0]]]);
    expect(roofErrs(withRoofs([{ rect: [0, 0, 2, 4] }]))).toEqual([['roof_too_small', [0, 0]]]);
  });

  // Плитка крыши [0, 0, 5, 4] в px: x 6…75, y −9…29 (roofBox x 0…80, y −16…40 без рамки 7/5/11/6). Короб — часть
  // 32×16 с at [0, −8].
  it('предметы крыши: неизвестный, обычный, вне плитки крыши', () => {
    const at = (item: string, x: number, y = 1) => withRoofs([{ rect: [0, 0, 5, 4], props: [{ item, at: [x, y] }] }]);
    expect(roofErrs(at('nope', 1))).toEqual([['unknown_item', [1, 1]]]);
    expect(roofErrs(at('desk', 1))).toEqual([['not_roof_prop', [1, 1]]]);
    expect(roofErrs(at('roof_vent', 2))).toEqual([]); // px x 32…64
    expect(roofErrs(at('roof_vent', 3))).toEqual([['roof_prop_outside', [3, 1]]]); // px x 48…80 — правее 75
    expect(roofErrs(at('roof_vent', 1, 2))).toEqual([['roof_prop_outside', [1, 2]]]); // py 24…40 — ниже 29
  });

  // Крыша нарисована на тайл выше своих клеток (спека крыш 4.2 п. 5, 4.4): по клеткам короб 2×2 на рядах 1–2 лежит во
  // внутренней части, но его низ на нижнем внутреннем ряду ушёл бы за низ крыши — на лицо южной стены.
  it('roof_prop_outside в пикселях: предмет на нижнем внутреннем ряду вылезает за низ крыши, высокий — за верх', () => {
    const cat = (part: unknown) => {
      const r = loadCatalog(mutateYaml(ROOF_CATALOG, (d) => (d.items.roof_vent.variants = [{ default: { parts: [part] } }])));
      if (!r.ok) throw new Error(JSON.stringify(r.errors));
      return r.value;
    };
    const errsWith = (part: unknown) => {
      const r = parseOffice(ROOF_OFFICE, cat(part));
      return r.ok ? [] : r.errors.map((e) => [e.code, e.at]);
    };
    expect(errsWith({ sheet: 's', rect: [96, 0, 32, 24], at: [0, 8] })).toEqual([['roof_prop_outside', [1, 1]]]); // py 24…48, как короб LimeZu
    expect(errsWith({ sheet: 's', rect: [96, 0, 32, 13], at: [0, 0] })).toEqual([]); // py 16…29 — ровно до низа плитки
    expect(errsWith({ sheet: 's', rect: [96, 0, 32, 16], at: [0, -26] })).toEqual([['roof_prop_outside', [1, 1]]]); // py −10 — выше −9
    expect(errsWith({ sheet: 's', rect: [96, 0, 32, 16], at: [0, -25] })).toEqual([]);
  });

  it('roof_prop_placed: предмет крыши в легенде и в placements здания', () => {
    expect(roofErrs(withRoofs([], (d) => (d.legend.v = 'roof_vent'))).map(([c]) => c)).toEqual(['roof_prop_placed']);
    expect(roofErrs(withRoofs([], (d) => (d.placements = [{ item: 'roof_vent', at: [6, 1] }])))).toEqual([['roof_prop_placed', [6, 1]]]);
  });

  it('roof_prop_placed: предмет крыши в легенде участка', () => {
    const cat = loadCatalog(mutateYaml(SITE_CATALOG, (d) => (d.items.roof_vent = ROOF_VENT_ITEM)));
    if (!cat.ok) throw new Error(JSON.stringify(cat.errors));
    const r = parseOffice(mutateYaml(SITE_OFFICE, (d) => (d.site.legend.V = 'roof_vent')), cat.value);
    expect(r.ok ? [] : r.errors.map((e) => e.code)).toEqual(['roof_prop_placed']);
  });

  it('roof_catalog: крыши при каталоге без раздела roof', () => {
    const r = parseOffice(withRoofs([{ rect: [0, 0, 5, 4] }]), styledCatalog());
    expect(r.ok ? [] : r.errors.map((e) => e.code)).toEqual(['roof_catalog']);
  });
});

describe('вывеска в office.yaml (спека хостинга 3.1)', () => {
  it('sign разбирается в layout.sign; без sign — undefined', () => {
    const withSign = parseOffice(mutateYaml(WORLD_OFFICE, (d) => (d.sign = { text: 'Hi' })), miniCatalog());
    expect(withSign.ok && withSign.value.sign).toEqual({ text: 'Hi' });
    const plain = parseOffice(WORLD_OFFICE, miniCatalog());
    expect(plain.ok && plain.value.sign).toBeUndefined();
  });
  it('пустая вывеска — ошибка схемы в office.yaml', () => {
    const r = parseOffice(mutateYaml(WORLD_OFFICE, (d) => (d.sign = {})), miniCatalog());
    expect(r.ok ? [] : r.errors.map((e) => [e.file, e.code])).toEqual([['office.yaml', 'schema']]);
  });
});
