import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
import { itemView, loadCatalog, wallFacePart } from '../src/index.ts';

const r = loadCatalog(readFileSync(new URL('../../../catalog/limezu/catalog.yaml', import.meta.url), 'utf8'));
if (!r.ok) throw new Error(JSON.stringify(r.errors));
const c = r.value;
const face = (f: number) => ({ face: f, at: [0, -16], sortY: 1 });
const FACES = [48, 128, 112, 144, 0, 32, 16]; // торец, Т, Г, ┐, левое, правое, середина — в порядке правил

describe('каталог LimeZu: северные комнаты (спека северных комнат 4)', () => {
  it('листы стен и лифтовой двери (4.1)', () => {
    expect(c.sheets['walls']).toBe('modern-interiors/1_Interiors/16x16/Room_Builder_subfiles/Room_Builder_Walls_16x16.png');
    expect(c.sheets['elevator_door']).toBe('modern-interiors/3_Animated_objects/16x16/spritesheets/animated_elevator_door_entrance_2.png');
  });

  it('полы комнат (4.2)', () => {
    expect([c.floors['carpet_burgundy'], c.floors['steel_plate'], c.floors['concrete']]).toEqual([
      [{ sheet: 'room', rect: [176, 192, 16, 16] }],
      [{ sheet: 'floors', rect: [144, 464, 16, 16] }],
      [{ sheet: 'floors', rect: [80, 528, 16, 16] }],
    ]);
  });

  it('стили стен, стиль по умолчанию — office (4.3)', () => {
    expect(c.wallStyles).toEqual({
      office: { sheet: 'room', base: [0, 176] },
      wood_panels: { sheet: 'walls', base: [0, 416] },
      steel: { sheet: 'walls', base: [0, 544] },
      brick: { sheet: 'room', base: [0, 144] },
    });
    expect(c.items['wall']!.autotile!.style).toBe('office');
  });

  it('семь правил лиц — части face; у стиля office прежние rect, кромки — обычные части', () => {
    const rules = c.items['wall']!.autotile!.rules;
    expect(rules.slice(0, 7)).toEqual([
      { when: { s: 0, e: 0, w: 0 }, parts: [face(48)] },
      { when: { s: 0, n: 1, nw: 0, ne: 0, e: 1, w: 1 }, parts: [face(128)] },
      { when: { s: 0, n: 1, nw: 0, w: 0 }, parts: [face(112)] },
      { when: { s: 0, n: 1, ne: 0, e: 0 }, parts: [face(144)] },
      { when: { s: 0, w: 0 }, parts: [face(0)] },
      { when: { s: 0, e: 0 }, parts: [face(32)] },
      { when: { s: 0 }, parts: [face(16)] },
    ]);
    // До спеки северных комнат лица были абсолютными rect листа room в ряду y 176 — стиль office даёт те же.
    const office = c.wallStyles['office']!;
    expect(FACES.map((f) => wallFacePart({ face: f, at: [0, -16], sortY: 1 }, office, 16))).toEqual(
      FACES.map((x) => ({ sheet: 'room', rect: [x, 176, 16, 32], at: [0, -16], sortY: 1 })),
    );
    expect(rules.slice(7).every((rule) => rule.parts.every((p) => !('face' in p)))).toBe(true);
  });

  it('лифтовая дверь 2×1: проходима, без variants, кадры 32×32, датчик 2×3 (4.4)', () => {
    const d = c.items['elevator_door']!;
    expect([d.size, d.blocks, d.variants, d.layer]).toEqual([[2, 1], [], [], 'sorted']);
    expect(d.door).toEqual({ sheet: 'elevator_door', frame: [32, 32], open: [0, 1, 2, 3, 4, 5, 6, 7], fps: 24, hold: 0, at: [0, -16], sortY: 0.97, sensor: [0, -1, 2, 3], sound: 'lift' });
  });

  it('дверь склада 1×1 (спека крыш 3.2): кадры 16×32, датчик 1×3, перемычка из середины лица, без звука', () => {
    expect(c.sheets['door_wood']).toBe('modern-interiors/3_Animated_objects/16x16/spritesheets/animated_door_3.png');
    const d = c.items['storage_door']!;
    expect([d.size, d.blocks, d.variants, d.layer]).toEqual([[1, 1], [], [], 'sorted']);
    expect(d.door).toEqual({
      sheet: 'door_wood', frame: [16, 32], open: [0, 1, 2, 3, 4], fps: 20, hold: 0, at: [0, -16], sortY: 0.97, sensor: [0, -1, 1, 3],
      lintel: { face: 16, rects: [[0, 0, 16, 11], [0, 11, 1, 21], [15, 11, 1, 21]] },
    });
  });
});

// Мебель (спека северных комнат 4.5): [id, size, выравнивание по x, части [лист, rect, at, sortY]].
// Выравнивание: l — к левой стене (at.x = 0), r — к правой (at.x = 16·w − rect.w), c — по центру посадки.
type Row = [string, [number, number], 'l' | 'r' | 'c', [string, [number, number, number, number], [number, number], number][]];
const FURNITURE: Row[] = [
  ['servers', [3, 1], 'l', [['control_server', [0, 10, 48, 34], [0, -18], 1]]],
  ['server_cabinet', [2, 1], 'c', [['office', [5, 373, 23, 34], [4, -18], 1]]],
  ['retro_pcs', [4, 1], 'c', [['classroom', [48, 170, 64, 38], [0, -22], 1]]],
  ['printer', [1, 1], 'c', [['office', [160, 353, 15, 19], [0, -3], 1]]],
  ['printer_2', [1, 1], 'r', [['office', [128, 385, 15, 18], [1, -2], 1]]],
  ['retro_desk', [3, 2], 'c', [['office', [160, 448, 48, 32], [0, 0], 2], ['classroom', [0, 167, 16, 25], [15, 1], 2.02]]],
  ['box_open', [2, 1], 'l', [['ext_garage', [245, 523, 23, 21], [0, -5], 1]]],
  ['box_stack', [2, 1], 'l', [['ext_garage', [448, 505, 32, 36], [0, -20], 1]]],
  ['parcels', [2, 1], 'r', [['ext_post', [82, 208, 30, 32], [2, -16], 1]]],
  ['cinder_blocks', [2, 1], 'l', [['ext_worksite', [161, 267, 31, 37], [0, -21], 1]]],
  ['generator', [3, 1], 'c', [['ext_houses', [391, 4298, 34, 22], [7, -6], 1]]],
  ['control_panel', [2, 1], 'c', [['ext_subway', [3, 288, 26, 32], [3, -16], 1]]],
  ['control_monitor', [2, 1], 'c', [['ext_subway', [70, 288, 21, 32], [5, -16], 1]]],
  ['tool_cabinet', [2, 1], 'c', [['ext_worksite', [132, 221, 26, 35], [3, -19], 1]]],
  ['hangar_locker', [2, 1], 'r', [['ext_military', [424, 1298, 17, 29], [15, -13], 1]]],
  ['medical_crate', [3, 2], 'c', [['ext_military', [467, 2275, 43, 29], [2, 3], 2]]],
  ['wood_crates', [2, 1], 'c', [['ext_camping', [2, 324, 28, 27], [2, -11], 1]]],
  ['wood_crates_2', [2, 1], 'c', [['ext_camping', [1, 360, 30, 23], [1, -7], 1]]],
  ['crate', [1, 1], 'c', [['ext_camping', [0, 306, 16, 14], [0, 2], 1]]],
  ['barrel_2', [1, 1], 'c', [['ext_props', [209, 1574, 15, 26], [0, -10], 1]]],
  ['barrel', [1, 1], 'r', [['ext_props', [193, 1579, 15, 21], [1, -5], 1]]],
];

describe('каталог LimeZu: мебель северных комнат (спека северных комнат 4.5)', () => {
  it('листы мебели (4.1)', () => {
    const T = 'modern-exteriors/Modern_Exteriors_16x16/ME_Theme_Sorter_16x16/';
    expect(Object.fromEntries(['control_server', 'ext_garage', 'ext_post', 'ext_military', 'ext_camping', 'ext_worksite', 'ext_houses'].map((k) => [k, c.sheets[k]]))).toEqual({
      control_server: 'modern-interiors/3_Animated_objects/16x16/spritesheets/animated_control_room_server.png',
      ext_garage: `${T}6_Garage_Sales_16x16.png`,
      ext_post: `${T}22_Post_Office_16x16.png`,
      ext_military: `${T}23_MIlitary_Base_16x16.png`,
      ext_camping: `${T}11_Camping_16x16.png`,
      ext_worksite: `${T}8_Worksite_16x16.png`,
      ext_houses: `${T}24_Additional_Houses_16x16.png`,
    });
  });

  it('предметы: посадка, sorted, блокируют все клетки, части — как в таблице спеки', () => {
    for (const [id, size, , parts] of FURNITURE) {
      const def = c.items[id]!;
      expect([id, def.size, def.layer, def.blocks.length]).toEqual([id, size, 'sorted', size[0] * size[1]]);
      expect([id, itemView(def, null, 1).parts.map((p) => [p.sheet, p.rect, p.at, p.sortY])]).toEqual([id, parts]);
    }
  });

  it('низ спрайта — на низу посадки; по x — по центру или прижат к стене своей стороны', () => {
    const x = { l: () => 0, r: (w: number, rw: number) => 16 * w - rw, c: (w: number, rw: number) => Math.floor((16 * w - rw) / 2) };
    for (const [id, [w, h], align, parts] of FURNITURE) {
      const [, rect, at] = parts[0]!;
      expect([id, at]).toEqual([id, [x[align](w, rect[2]), 16 * h - rect[3]]]);
    }
  });
});

describe('каталог LimeZu: плоская крыша (спека крыш 4.3)', () => {
  it('раздел roof: лист ext_office, рамка 7/6/11/6, светлая плитка, углы без тёмной полосы', () => {
    expect(c.roof).toEqual({
      sheet: 'ext_office',
      border: [7, 6, 11, 6],
      fill: [64, 144, 16, 16],
      corners: {
        nw: [{ rect: [0, 103, 5, 6], at: [0, 0] }, { rect: [48, 103, 1, 6], at: [5, 0] }, { rect: [0, 150, 6, 1], at: [0, 6] }],
        ne: [{ rect: [139, 103, 5, 6], at: [1, 0] }, { rect: [95, 103, 1, 6], at: [0, 0] }, { rect: [138, 150, 6, 1], at: [0, 6] }],
        sw: [{ rect: [0, 165, 6, 11], at: [0, 0] }],
        se: [{ rect: [138, 165, 6, 11], at: [0, 0] }],
      },
      sides: {
        n: [{ rect: [48, 103, 16, 6], at: [0, 0] }, { rect: [48, 128, 16, 1], at: [0, 6] }],
        s: [{ rect: [48, 165, 16, 11], at: [0, 0] }],
        w: [{ rect: [0, 148, 6, 16], at: [0, 0] }],
        e: [{ rect: [138, 148, 6, 16], at: [0, 0] }],
      },
    });
  });

  it('короб roof_vent: предмет крыши 2×2, Air_Duct_1_Roof_Prop низом на низу посадки', () => {
    const v = c.items['roof_vent']!;
    expect([v.roof, v.size, v.blocks, v.layer]).toEqual([true, [2, 2], [], 'sorted']);
    expect(itemView(v, null, 1).parts).toEqual([{ sheet: 'ext_office', rect: [384, 504, 32, 24], at: [0, 8], sortY: 0 }]);
  });
});
