import { existsSync } from 'node:fs';
import { basename, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
import { checkAtlas, missingPortraitSheets, missingUiSheets, readPngSize, validateOfficesDir } from '../src/index.ts';
import { loadCatalog } from '@pixeloffice/core';
import { POOL_FILES, fakeAssets, fakePng } from './png.ts';
import { LINTEL_CATALOG, MINI_CATALOG, ROOF_SECTION, SITE_CATALOG, STYLED_CATALOG, miniCatalog, mutateYaml, signCatalog, styledCatalog, uiCatalog } from '../../../packages/core/tests/fixtures.ts';

describe('проверка атласа', () => {
  it('readPngSize читает IHDR', () => {
    const dir = fakeAssets(256, 848);
    expect(readPngSize(join(dir, 'test/sheet.png'))).toEqual({ width: 256, height: 848 });
  });

  it('все кадры в границах и все файлы pool есть — пусто', () => {
    expect(checkAtlas(miniCatalog(), fakeAssets(128, 160))).toEqual([]);
  });

  it('кадр за границей листа', () => {
    expect(checkAtlas(miniCatalog(), fakeAssets(128, 100)).join('\n')).toContain('вне листа');
  });

  it('петля кадров части (спека фонтана 3.1): последний кадр должен поместиться в лист', () => {
    const withAnim = (frames: number) => {
      const r = loadCatalog(mutateYaml(MINI_CATALOG, (d) => (d.items.desk.variants[0].default.parts[0].anim = { frames, fps: 10 })));
      if (!r.ok) throw new Error(JSON.stringify(r.errors));
      return r.value;
    };
    expect(checkAtlas(withAnim(4), fakeAssets(128, 160))).toEqual([]); // кадр 3 — x 96..128
    expect(checkAtlas(withAnim(5), fakeAssets(128, 160))).toEqual(['items.desk.variants[0].default[0].anim: кадр [128,48,32,32] вне листа test/sheet.png 128×160']);
  });

  it('нет файла детали pool — ошибка с разделом pool и путём', () => {
    expect(checkAtlas(miniCatalog(), fakeAssets(128, 160, ['gen/Eyes_02.png', 'gen/Accessory_01_Ladybug_03.png']))).toEqual([
      'characters.pool.eyes: нет файла gen/Eyes_02.png',
      'characters.pool.accessories: нет файла gen/Accessory_01_Ladybug_03.png',
    ]);
  });

  it('анимация не помещается в лист детали pool — с разделом pool', () => {
    const dir = fakeAssets(128, 160);
    fakePng(join(dir, 'gen/Hairstyle_01_04.png'), 896, 300); // play — ряд 17: нужно 576 px высоты
    expect(checkAtlas(miniCatalog(), dir)).toEqual(['characters.animations.play: не помещается в characters.pool.hairs gen/Hairstyle_01_04.png 896×300']);
  });

  it('анимация не помещается во многие листы pool — одна строка с первым примером и числом листов', () => {
    const dir = fakeAssets(128, 160);
    for (const f of POOL_FILES) fakePng(join(dir, f), 896, 300);
    expect(checkAtlas(miniCatalog(), dir)).toEqual([
      `characters.animations.play: не помещается в characters.pool.bodies gen/Body_01.png 896×300; всего таких листов pool: ${POOL_FILES.length}`,
    ]);
  });

  it('предмет в руках: проверяются все варианты листа и кадры предмета', () => {
    const r = loadCatalog(
      mutateYaml(MINI_CATALOG, (d) => {
        d.characters.props = { smartphone: { path: 'gen/Smartphone_{n}.png', variants: ['1', '2'] } };
        d.characters.animations.phone = { row: 6, frames: 3, dirs: { down: 0 }, prop: { name: 'smartphone', row: 4, cols: [null, 1, 8] } };
      }),
    );
    if (!r.ok) throw new Error(JSON.stringify(r.errors));
    const dir = fakeAssets(128, 160);
    fakePng(join(dir, 'gen/Smartphone_1.png'), 384, 192);
    expect(checkAtlas(r.value, dir)).toEqual(['characters.props.smartphone: нет файла gen/Smartphone_2.png']);
    fakePng(join(dir, 'gen/Smartphone_2.png'), 128, 192); // колонка 8 — за краем листа шириной 8 кадров
    expect(checkAtlas(r.value, dir)).toEqual(['characters.animations.phone.prop: не помещается в gen/Smartphone_2.png 128×192']);
  });

  it('облачка разговора: файл emotes и кадры в границах (спека атласа 2.1.1)', () => {
    const r = loadCatalog(
      mutateYaml(MINI_CATALOG, (d) => {
        d.characters.talk = {
          speakers: 2,
          turn: ['10s', '20s'],
          emote: '3.0s',
          bounce: { fps: 8, dy: [0, -1, -1, 0] },
          emotes: { path: 'gen/emotes.png', cell: 16, fps: 8, appear: [[0, 0], [1, 0]], tail: [4, 1], icons: { heart: [4, 2], zzz: [6, 5] }, set: ['heart', 'zzz'], sleep: 'zzz' },
        };
      }),
    );
    if (!r.ok) throw new Error(JSON.stringify(r.errors));
    const dir = fakeAssets(128, 160);
    expect(checkAtlas(r.value, dir)).toEqual(['characters.talk.emotes: нет файла gen/emotes.png']);
    fakePng(join(dir, 'gen/emotes.png'), 128, 96); // хватило бы и меньше: кадры — до клетки 7×7, appear — две клетки вниз
    expect(checkAtlas(r.value, dir)).toEqual([]);
    fakePng(join(dir, 'gen/emotes.png'), 112, 160); // 7 клеток: zzz — 6–7 ряда 5, за краем только вторые клетки пар (icons и sleep)
    expect(checkAtlas(r.value, dir)).toEqual([
      'characters.talk.emotes.icons.zzz[1]: кадр [112,80,16,16] вне листа gen/emotes.png 112×160',
      'characters.talk.emotes.sleep[1]: кадр [112,80,16,16] вне листа gen/emotes.png 112×160',
    ]);
  });

  it('missingPortraitSheets: четыре пробных файла, не-валящая (спека диалоговых окон 2.4)', () => {
    const portraits = { skins: 'gen/PG_Skin_{body:0}.png', eyes: 'gen/PG_Eyes_{eyes}.png', hairs: 'gen/PG_Hairstyle_{model}_{color:0}.png', accessories: 'gen/PG_Accessory_{model}_{name}_{color:0}.png' };
    const r = loadCatalog(mutateYaml(MINI_CATALOG, (d) => (d.characters.portraits = portraits)));
    if (!r.ok) throw new Error(JSON.stringify(r.errors));
    const dir = fakeAssets(128, 160);
    expect(missingPortraitSheets(r.value, dir)).toEqual([
      'gen/PG_Skin_1.png', 'gen/PG_Eyes_01.png', 'gen/PG_Hairstyle_01_1.png', 'gen/PG_Accessory_01_Ladybug_1.png',
    ]);
    for (const f of ['gen/PG_Skin_1.png', 'gen/PG_Eyes_01.png', 'gen/PG_Hairstyle_01_1.png', 'gen/PG_Accessory_01_Ladybug_1.png']) fakePng(join(dir, f), 320, 96);
    expect(missingPortraitSheets(r.value, dir)).toEqual([]);
    expect(missingPortraitSheets(miniCatalog(), dir)).toEqual([]); // нет раздела portraits — пусто
  });

  describe('участок', () => {
    const site = () => {
      const r = loadCatalog(SITE_CATALOG);
      if (!r.ok) throw new Error(JSON.stringify(r.errors));
      return r.value;
    };
    const dirWith = (sheetW: number, sheetH: number, doorW: number) => {
      const dir = fakeAssets(sheetW, sheetH);
      fakePng(join(dir, 'test/door.png'), doorW, 32);
      return dir;
    };

    it('все кадры участка в границах — пусто', () => {
      expect(checkAtlas(site(), dirWith(160, 448, 144))).toEqual([]);
    });

    it('кадр двери за листом', () => {
      expect(checkAtlas(site(), dirWith(160, 448, 96)).some((e) => e.startsWith('door.open[2]'))).toBe(true);
    });

    it('тайл земли и часть фасада за листом', () => {
      const errs = checkAtlas(site(), dirWith(160, 170, 144));
      expect(errs.some((e) => e.startsWith('terrains.grass.fill[0]'))).toBe(true);
      expect(errs.some((e) => e.startsWith('facade.windows.left'))).toBe(true);
    });

    it('нет листа двери', () => {
      expect(checkAtlas(site(), fakeAssets(160, 320)).some((e) => e.includes('нет файла test/door.png'))).toBe(true);
    });

    it('кадр машины и автобуса за листом (спека транспорта 3.5)', () => {
      const errs = checkAtlas(site(), dirWith(150, 400, 144));
      expect(errs).toContain('vehicles.cars[1].right: кадр [80,192,80,48] вне листа test/sheet.png 150×400');
      expect(errs).toContain('vehicles.bus.left: кадр [0,352,112,64] вне листа test/sheet.png 150×400');
    });

    it('плашка вывески за листом (спека вывески 3.2)', () => {
      expect(checkAtlas(signCatalog(), dirWith(160, 448, 144))).toEqual([]);
      // На листе высотой 440 вылезает и остановка SITE_CATALOG (кадр [0,400,80,48]) — сверяем только строки плашки.
      const sign = checkAtlas(signCatalog(), dirWith(160, 440, 144)).filter((e) => e.startsWith('facade.sign'));
      expect(sign).toEqual([
        'facade.sign.left: кадр [0,432,2,12] вне листа test/sheet.png 160×440',
        'facade.sign.mid: кадр [2,432,3,12] вне листа test/sheet.png 160×440',
        'facade.sign.right: кадр [5,432,2,12] вне листа test/sheet.png 160×440',
      ]);
    });
  });

  describe('стили стен (спека северных комнат 4.6)', () => {
    const dir = (wallsW: number, wallsH: number) => {
      const d = fakeAssets(128, 160);
      fakePng(join(d, 'test/walls.png'), wallsW, wallsH);
      return d;
    };

    it('кадры лиц всех стилей в границах — пусто', () => {
      expect(checkAtlas(styledCatalog(), dir(16, 32))).toEqual([]);
    });

    it('кадр лица стиля за листом — ошибка с именем стиля и face', () => {
      expect(checkAtlas(styledCatalog(), dir(16, 16))).toEqual(['wallStyles.stone.face[0]: кадр [0,0,16,32] вне листа test/walls.png 16×16']);
    });

    it('кадр двери-предмета за листом', () => {
      const r = loadCatalog(mutateYaml(STYLED_CATALOG, (d) => (d.items.elevator_door.door.open = [0, 1, 2, 3, 4])));
      if (!r.ok) throw new Error(JSON.stringify(r.errors));
      expect(checkAtlas(r.value, dir(16, 32))).toEqual(['items.elevator_door.door.open[4]: кадр [128,0,32,32] вне листа test/sheet.png 128×160']);
    });

    it('кадр лица перемычки — у каждого стиля (спека крыш 3.2.5)', () => {
      const r = loadCatalog(mutateYaml(LINTEL_CATALOG, (d) => (d.items.wood_door.door.lintel.face = 48)));
      if (!r.ok) throw new Error(JSON.stringify(r.errors));
      expect(checkAtlas(r.value, dir(16, 32))).toEqual(['wallStyles.stone.face[48]: кадр [48,0,16,32] вне листа test/walls.png 16×32']);
    });
  });

  it('раздел roof (спека крыш 4.3.6): каждый прямоугольник — в границах листа', () => {
    const r = loadCatalog(mutateYaml(MINI_CATALOG, (d) => (d.roof = { ...structuredClone(ROOF_SECTION), fill: [120, 0, 16, 16] })));
    if (!r.ok) throw new Error(JSON.stringify(r.errors));
    expect(checkAtlas(r.value, fakeAssets(128, 160))).toEqual(['roof.fill: кадр [120,0,16,16] вне листа test/sheet.png 128×160']);
  });
});

describe('шкура интерфейса (спека интерфейса §3.2)', () => {
  // Ассеты мини-каталога и листы тем: размер или null — листа нет.
  const uiAssets = (cold: [number, number] | null, warm: [number, number] | null) => {
    const dir = fakeAssets(128, 160);
    if (cold) fakePng(join(dir, 'test/ui-cold.png'), ...cold);
    if (warm) fakePng(join(dir, 'test/ui-warm.png'), ...warm);
    return dir;
  };

  it('рамки и плитки обеих сеток в границах листов — пусто', () => {
    expect(checkAtlas(uiCatalog(), uiAssets([784, 544], [976, 688]))).toEqual([]);
  });

  it('за краем листа — ошибка с путём в каталоге; другая тема не задета', () => {
    const errors = checkAtlas(uiCatalog(), uiAssets([784, 300], [976, 688]));
    expect(errors).toContain('ui.icons.gridOn.cold.edit: кадр [448,304,16,16] вне листа test/ui-cold.png 784×300');
    expect(errors.some((e) => e.startsWith('ui.frames.button.cold: '))).toBe(true);
    expect(errors).toContain('ui.sprites.knob.cold: кадр [321,498,13,12] вне листа test/ui-cold.png 784×300');
    expect(errors.some((e) => e.startsWith('ui.sprites.knob.warm: '))).toBe(false);
    expect(errors.some((e) => e.includes('.warm'))).toBe(false);
  });

  it('нет листа темы — не ошибка checkAtlas, а missingUiSheets; без раздела ui — пусто', () => {
    const dir = uiAssets([784, 544], null);
    expect(checkAtlas(uiCatalog(), dir)).toEqual([]);
    expect(missingUiSheets(uiCatalog(), dir)).toEqual(['test/ui-warm.png']);
    expect(missingUiSheets(miniCatalog(), dir)).toEqual([]);
  });
});

// Спека 5.5: атлас по настоящим PNG — в тестах при наличии assetsDir, без ассетов тест skipped.
// Маркер скипа — каталог пака LimeZu, а не assets/ целиком: каталог-контейнер существует и на CI
// (в нём коммиченный pixeloffice-art), и скип там не срабатывал — атлас падал на ~2400 отсутствующих
const OFFICES = fileURLToPath(new URL('../../../offices/', import.meta.url));
const REAL_ASSETS = fileURLToPath(new URL('../../../assets/modern-office-revamped/', import.meta.url)); // assetsDir офисов demo и local

describe('атлас настоящих офисов', () => {
  it.skipIf(!existsSync(REAL_ASSETS))('offices/*: кадры каталога в границах PNG, файлы всех деталей pool есть', async () => {
    const reports = await validateOfficesDir(OFFICES);
    expect(reports.flatMap((r) => r.errors)).toEqual([]);
    const checked = reports.filter((r) => r.notes.includes('атлас: ok')).map((r) => basename(r.dir));
    expect(checked).toEqual(expect.arrayContaining(['demo', 'local']));
  });
});
