import { readFileSync } from 'node:fs';
import { parse } from 'yaml';
import { describe, expect, it } from 'vitest';
import type { LightView } from '@pixeloffice/protocol';
import { buildWorldMap, doorGap, facadeColumns, loadCatalog, parseOffice, reachableFrom, renderMap, type SiteLayout } from '../src/index.ts';

const isGlassLight = (l: LightView): l is Extract<LightView, { kind: 'glass' }> => l.kind === 'glass';

const read = (rel: string) => readFileSync(new URL(rel, import.meta.url), 'utf8');
const cat = loadCatalog(read('../../../catalog/limezu/catalog.yaml'));
if (!cat.ok) throw new Error(JSON.stringify(cat.errors));
const catalog = cat.value;
const site = (name: string): SiteLayout => {
  const r = parseOffice(read(`../../../offices/${name}/office.yaml`), catalog);
  if (!r.ok) throw new Error(JSON.stringify(r.errors));
  if (!r.value.site) throw new Error(`${name}: нет site`);
  return r.value.site;
};
const layoutOf = (name: string) => {
  const r = parseOffice(read(`../../../offices/${name}/office.yaml`), catalog);
  if (!r.ok) throw new Error(JSON.stringify(r.errors));
  return r.value;
};

// Северная полоса (спека северных комнат 3.1, 7.2; спека крыш 3): в ряду 7 проём техкомнаты — две клетки пола, дверь
// дока — elevator_door на двух клетках пола, дверь склада — storage_door на клетке пола; клетки по бокам дверей —
// стены. wall — столбец стены между доком и складом.
const NORTH: Record<string, { opening: number; door: number; store: number; wall: number }> = {
  demo: { opening: 10, door: 17, store: 23, wall: 21 },
  team: { opening: 10, door: 17, store: 23, wall: 21 },
  local: { opening: 4, door: 11, store: 20, wall: 15 },
};

describe('участки офисов (спека 7)', () => {
  it('demo и team — одинаковая сетка участка', () => {
    expect(parse(read('../../../offices/team/office.yaml')).site).toEqual(parse(read('../../../offices/demo/office.yaml')).site);
  });

  it('demo и team — разобранные office.yaml совпадают целиком (правка северной полосы не разойдётся)', () => {
    const { sign: _demoSign, ...demo } = parse(read('../../../offices/demo/office.yaml'));
    expect(parse(read('../../../offices/team/office.yaml'))).toEqual(demo); // вывеска team — пока в config.yaml (план хостинга, отступление 2)
  });

  for (const name of ['demo', 'team', 'local']) {
    it(`${name}: кадр — здание, фасад и улица до дороги включительно; маркеры — только места парковки`, () => {
      const s = site(name);
      const [vx, vy, vw, vh] = s.view;
      const [, , bw, bh] = s.building;
      expect(vx <= 0 && vy <= 0 && vx + vw >= bw && vy + vh >= bh).toBe(true);
      const [, oy, W] = s.rect;
      const roadRows = s.terrain.map((t, i) => (t === 'road' ? Math.floor(i / W) + oy : null)).filter((y) => y !== null);
      expect(roadRows.length).toBeGreaterThan(0);
      expect(vy + vh - 1).toBeGreaterThanOrEqual(Math.max(...roadRows));
      expect(s.markers.length).toBeGreaterThan(0);
      expect(s.markers.every((m) => m.name === 'car_spot')).toBe(true);
      expect(s.items.some((i) => i.item === 'bus_stop')).toBe(true);
    });
  }

  for (const name of ['demo', 'team', 'local']) {
    it(`${name}: дорога 5 рядов, пунктир в среднем — полосы одинаковые; карман BUS над пунктиром`, () => {
      const s = site(name);
      const [ox, oy, W] = s.rect;
      const roadRows = [...new Set(s.terrain.map((t, i) => (t === 'road' ? Math.floor(i / W) + oy : null)).filter((y) => y !== null))];
      expect(roadRows).toHaveLength(5);
      expect(Math.max(...roadRows) - Math.min(...roadRows)).toBe(4);
      const mid = Math.min(...roadRows) + 2;
      const dashes = s.items.filter((i) => i.item === 'lane_dash');
      expect(dashes.length).toBeGreaterThan(0);
      expect(dashes.every((d) => d.y === mid)).toBe(true);
      // Пунктир на всю ширину участка, кроме колонок рамки кармана (её нижний ряд — тоже средний ряд дороги).
      const frame = s.items.filter((i) => i.item.startsWith('bus_frame_'));
      expect(Math.max(...frame.map((f) => f.y))).toBe(mid);
      const zebra = s.items.filter((i) => i.item.startsWith('crosswalk_'));
      const midCols = [...dashes, ...frame.filter((f) => f.y === mid), ...zebra.filter((z) => z.y === mid)];
      expect(midCols.length).toBe(W);
      expect(new Set(midCols.map((d) => d.x - ox)).size).toBe(W);
    });

    it(`${name}: парковка под проезд — въезд 3×3 под проездом через три ряда тротуара, места 3×5 вверх на асфальте (спека транспорта 6)`, () => {
      const s = site(name);
      const [ox, oy, W] = s.rect;
      const t = (x: number, y: number) => s.terrain[(y - oy) * W + (x - ox)];
      // Мировые клетки: участка − (11, 1) у demo и team, − (7, 1) у local.
      type Park = { spots: [number, number][]; drive: [number, number]; bay: [number, number] };
      const big: Park = { spots: [[41, 7], [44, 7], [47, 7], [50, 7], [41, 16], [44, 16], [47, 16], [50, 16]], drive: [38, 24], bay: [1, 27] };
      const P: Park = name === 'local' ? { spots: [[29, 9], [32, 9], [35, 9]], drive: [26, 18], bay: [-3, 21] } : big;
      const spots = s.markers.filter((m) => m.name === 'car_spot');
      expect(spots.map((m) => [m.x, m.y])).toEqual(P.spots);
      expect(spots.every((m) => m.facing === undefined)).toBe(true); // все места — up (по умолчанию)
      for (const [sx, sy] of P.spots) for (let j = 0; j < 5; j++) for (let i = 0; i < 3; i++) expect(t(sx + i, sy + j), `(${sx + i}, ${sy + j})`).toBe('parking');
      const drive = s.terrain.flatMap((v, i) => (v === 'driveway' ? [[(i % W) + ox, Math.floor(i / W) + oy]] : []));
      const [dx, dy] = P.drive;
      expect(drive).toEqual([0, 1, 2].flatMap((j) => [[dx, dy + j], [dx + 1, dy + j], [dx + 2, dy + j]]));
      for (let i = 0; i < 3; i++) expect([t(dx + i, dy - 1), t(dx + i, dy + 3)]).toEqual(['parking', 'road']);
      const bay = s.items.find((it) => it.item === 'bus_frame_nw')!;
      expect([bay.x, bay.y]).toEqual(P.bay);
      expect(bay.y).toBe(dy + 3); // верхний ряд кармана — первый ряд дороги под въездом (спека транспорта 3.4)
    });

    it(`${name}: остановка 5×2 у фасада, между ней и дорогой свободный ряд тротуара (спека транспорта 6)`, () => {
      const s = site(name);
      const [ox, oy, W] = s.rect;
      const t = (x: number, y: number) => s.terrain[(y - oy) * W + (x - ox)];
      const ry = Math.min(...s.terrain.flatMap((v, i) => (v === 'road' ? [Math.floor(i / W) + oy] : [])));
      // Тротуар — три ряда над дорогой; остановка занимает два верхних (задняя стенка — блок), нижний свободен.
      for (const y of [ry - 3, ry - 2, ry - 1]) for (let x = ox; x < ox + W; x++) expect(['sidewalk', 'driveway'], `(${x}, ${y})`).toContain(t(x, y));
      const stop = s.items.find((i) => i.item === 'bus_stop')!;
      expect(stop.y).toBe(ry - 3);
      const blocked = new Set<string>();
      for (const it of s.items) for (const [dx, dy] of catalog.items[it.item]!.blocks) blocked.add(`${it.x + dx},${it.y + dy}`);
      for (let x = ox; x < ox + W; x++) expect(blocked.has(`${x},${ry - 1}`), `(${x}, ${ry - 1})`).toBe(false);
      for (let x = stop.x; x < stop.x + 5; x++) expect(blocked.has(`${x},${stop.y}`), `(${x}, ${stop.y})`).toBe(true);
    });

    it(`${name}: парк — фонтан на площадке, скамейки и фонари; крайние ряд и столбец участка — газон`, () => {
      const s = site(name);
      const [, , W, H] = s.rect;
      const count = (ids: string[]) => s.items.filter((i) => ids.includes(i.item)).length;
      expect(count(['fountain'])).toBe(1);
      expect(count(['bench', 'bench_side'])).toBeGreaterThanOrEqual(name === 'local' ? 4 : 6);
      expect(count(['lamp'])).toBeGreaterThanOrEqual(4);
      const t = (x: number, y: number) => s.terrain[y * W + x];
      // Выше первого ряда тротуара улицы столбцы 0 и 1 — газон: кромка поперёк продолжения влево не появляется (записка спайка, п. 9).
      const firstWalkRow = [...Array(H).keys()].find((y) => [...Array(W).keys()].every((x) => ['sidewalk', 'driveway'].includes(t(x, y)!)))!;
      for (let y = 0; y < firstWalkRow; y++) for (const x of [0, 1]) expect(t(x, y), `(${x}, ${y})`).toBe('grass');
      for (let x = 0; x < W; x++) expect(t(x, 0), `(${x}, 0)`).toBe('grass');
      // Стопка последнего ряда повторяется вниз (спека улицы 6.2): он и ряд над ним — газон, иначе кромка газона
      // у тротуара или спуска в метро повторится полосами под участком.
      for (const y of [H - 2, H - 1]) for (let x = 0; x < W; x++) expect(t(x, y), `(${x}, ${y})`).toBe('grass');
    });
  }

  // Спальные места парка (спека сна 2.1, 5.1): нижняя клетка каждой боковой скамейки; demo и team — 4, local — 3.
  const SLEEP: Record<string, number> = { demo: 4, team: 4, local: 3 };
  for (const name of ['demo', 'team', 'local']) {
    it(`${name}: спальные места парка — нижние клетки всех боковых скамеек`, () => {
      const m = buildWorldMap(layoutOf(name), catalog);
      if (!m.ok) throw new Error(JSON.stringify(m.errors));
      const benches = site(name).items.filter((i) => i.item === 'bench_side');
      expect(benches).toHaveLength(SLEEP[name]!);
      expect(m.value.portals.parkSleep).toHaveLength(SLEEP[name]!);
      for (const b of benches) expect(m.value.spotAt(b.x, b.y + 1)?.tags, `${b.uid}`).toEqual(['park_sleep']);
    });
  }

  // Офисы с маршрутами этапа 2: метро, зебра, комната дока (спека маршрутов 6).
  for (const name of ['demo', 'team', 'local']) {
    it(`${name}: ряд 7 — проём техкомнаты, лифтовая дверь дока и дверь склада (спека крыш 3.2)`, () => {
      const l = layoutOf(name);
      const row7 = l.base.slice(7 * l.width, 8 * l.width);
      const floors = row7.flatMap((k, x) => (k === 'floor' ? [x] : []));
      const n = NORTH[name]!;
      expect(floors).toEqual([n.opening, n.opening + 1, n.door, n.door + 1, n.store]);
      expect(l.items.filter((i) => i.item === 'elevator_door').map((i) => [i.x, i.y])).toEqual([[n.door, 7]]);
      expect(l.items.filter((i) => i.item === 'storage_door').map((i) => [i.x, i.y])).toEqual([[n.store, 7]]);
      expect([row7[n.door - 1], row7[n.door + 2], row7[n.store - 1], row7[n.store + 1]]).toEqual(['wall', 'wall', 'wall', 'wall']);
    });

    it(`${name}: стена между доком и складом на всю высоту, зоны дока и склада (спека крыш 3.1, 3.2)`, () => {
      const l = layoutOf(name);
      const n = NORTH[name]!;
      for (let y = 1; y <= 6; y++) expect(l.base[y * l.width + n.wall], `(${n.wall}, ${y})`).toBe('wall');
      const zone = (id: string) => l.zones.find((z) => z.id === id)!.rect;
      expect([zone('dock'), zone('storage')]).toEqual(name === 'local' ? [[9, 1, 6, 7], [16, 1, 7, 7]] : [[15, 1, 6, 7], [22, 1, 13, 7]]);
    });

    it(`${name}: крыша над доком — стены дока, короб правее и выше центра (спека крыш 7)`, () => {
      const l = layoutOf(name);
      const x = name === 'local' ? 8 : 14;
      expect(l.roofs).toEqual([{ rect: [x, 0, 8, 8], props: [{ item: 'roof_vent', x: x + 4, y: 1 }] }]);
    });

    it(`${name}: склад достижим из офиса через свою дверь (спека крыш 8.2)`, () => {
      const l = layoutOf(name);
      const m = buildWorldMap(l, catalog);
      if (!m.ok) throw new Error(JSON.stringify(m.errors));
      const seen = reachableFrom(m.value, m.value.entrance());
      const n = NORTH[name]!;
      for (const [x, y] of [[n.store, 8], [n.store, 7], [n.store, 6], [n.store, 4]] as const) expect(seen[m.value.index(x, y)], `(${x}, ${y})`).toBe(1);
    });

    it(`${name}: зебра — столбец шириной 2 через все 5 рядов дороги (спека маршрутов 3.3)`, () => {
      const s = site(name);
      const [, oy, W] = s.rect;
      const roadRows = [...new Set(s.terrain.map((t, i) => (t === 'road' ? Math.floor(i / W) + oy : null)).filter((y) => y !== null))].sort((a, b) => a - b);
      const zebra = s.items.filter((i) => i.item.startsWith('crosswalk_'));
      const cols = [...new Set(zebra.map((z) => z.x))].sort((a, b) => a - b);
      expect(cols).toHaveLength(2);
      expect(cols[1]! - cols[0]!).toBe(1);
      for (const [k, x] of cols.entries()) {
        const side = k === 0 ? 'l' : 'r';
        const col = zebra.filter((z) => z.x === x).sort((a, b) => a.y - b.y);
        expect(col.map((z) => z.y)).toEqual(roadRows);
        expect(col.map((z) => z.item)).toEqual(roadRows.map((_, i) => (i === 0 ? `crosswalk_top_${side}` : `crosswalk_${side}`)));
      }
    });

    it(`${name}: один спуск в метро — за дорогой, под зеброй; комната дока у северной стены (спека маршрутов 6)`, () => {
      const s = site(name);
      const [, oy, W] = s.rect;
      const roadBottom = Math.max(...s.terrain.map((t, i) => (t === 'road' ? Math.floor(i / W) + oy : -Infinity)));
      expect(s.items.filter((i) => i.item === 'metro_entrance')).toHaveLength(1);
      const metro = s.items.find((i) => i.item === 'metro_entrance')!;
      expect(metro.y).toBe(roadBottom + 2); // ряд тротуара за дорогой, затем спуск
      const zebraX = s.items.filter((i) => i.item === 'crosswalk_r').map((z) => z.x);
      expect(zebraX).toContain(metro.x + 1); // средний столбец спуска — под правым столбцом зебры
      const l = layoutOf(name);
      const dock = l.items.find((i) => i.item === 'agent_dock')!;
      expect(dock.y).toBe(1);
    });
  }

  it('demo: на парковке 8–10 мест', () => {
    const n = site('demo').markers.filter((m) => m.name === 'car_spot').length;
    expect(n).toBeGreaterThanOrEqual(8);
    expect(n).toBeLessThanOrEqual(10);
  });

  for (const name of ['demo', 'team', 'local']) {
    it(`${name}: фонари горят снаружи, стёкла фасада и двери — по присутствию (спека ночи 3.4)`, () => {
      const layout = parseOffice(read(`../../../offices/${name}/office.yaml`), catalog);
      if (!layout.ok) throw new Error(JSON.stringify(layout.errors));
      const map = buildWorldMap(layout.value, catalog);
      if (!map.ok) throw new Error(JSON.stringify(map.errors));
      const r = renderMap(layout.value, map.value, catalog);
      if (!r.ok) throw new Error(JSON.stringify(r.errors));
      const lights = r.value.lights ?? [];
      const lamps = layout.value.site!.items.filter((i) => i.item === 'lamp').length;
      expect(lamps).toBeGreaterThan(0);
      // outdoor — по месту предмета: свет фонаря участка снаружи, даже если ореол головы (на 31 px выше основания)
      // попадает в прямоугольник здания.
      expect(lights.filter((l) => l.kind === 'pool' && l.outdoor)).toHaveLength(lamps);
      expect(lights.filter((l) => l.kind === 'flare' && l.outdoor)).toHaveLength(lamps);
      const glass = lights.filter(isGlassLight);
      expect(glass.every((l) => l.facade && !l.outdoor)).toBe(true);
      // Ровно одно стекло двери — в проёме .E.; остальные — стёкла колонок окон, по прямоугольнику facade.glass на колонку.
      const ts = catalog.tileSize;
      const gap = doorGap(layout.value);
      if (!gap.ok) throw new Error(gap.message);
      const doorGlass = glass.filter((l) => l.x >= gap.x * ts && l.x < (gap.x + 3) * ts);
      expect(doorGlass).toHaveLength(1);
      expect(doorGlass[0]!.w).toBe(catalog.door!.glass![2]);
      const fw = catalog.facade!.windows;
      const cols = facadeColumns(layout.value.width, gap.x, { left: fw.left.length, block: fw.block.length, right: fw.right.length });
      const expected = cols.reduce((n, c) => (c.windows && c.windows.part !== 'pad' ? n + catalog.facade!.glass![c.windows.part][c.windows.i]!.length : n), 0);
      expect(expected).toBeGreaterThan(0);
      expect(glass.length - 1).toBe(expected);
    });
  }
});

describe('local: северные комнаты (спека северных комнат 7.2)', () => {
  it('мебель, которая помещается в комнаты шириной 7 клеток', () => {
    const l = layoutOf('local');
    const north = l.items.filter((i) => i.y >= 1 && i.y <= 6 && i.item !== 'agent_dock').map((i) => `${i.item}@${i.x},${i.y}`).sort();
    expect(north).toEqual(
      [
        'servers@1,1', 'server_cabinet@4,1', 'printer@6,1', 'printer_2@7,1', 'retro_desk@5,2', 'chair@6,4', 'chair@2,2', 'retro_desk_back@1,3', 'parcels@6,5',
        'cinder_blocks@16,1', 'generator@18,1', 'hangar_locker@21,1', 'medical_crate@18,2', 'wood_crates@21,4', 'barrel_2@21,5', 'barrel@22,5',
      ].sort(),
    );
    expect(l.walls).toEqual({ default: 'office', zones: { 'pod:tech': 'wood_panels', dock: 'steel', storage: 'brick' } });
  });
});
