import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
import { buildWorldMap, itemSounds, itemView, loadCatalog, parseOffice, renderMap } from '../src/index.ts';
import { SITE_CATALOG, SITE_OFFICE, WORLD_OFFICE, mutateYaml } from './fixtures.ts';

// Петля кадров у части и звук на месте (спека фонтана 3, 4): скамейка участка — анимированная и со звуком,
// стол здания — со звуком.
const ANIM_CATALOG = mutateYaml(SITE_CATALOG, (d) => {
  const bench = d.items.bench.variants[0].default;
  bench.parts[0].anim = { frames: 3, fps: 10 };
  bench.sounds = [{ type: 'fountain', at: [8, 4] }];
  d.items.desk.variants[0].default.sounds = [{ type: 'fountain', at: [0, -2] }];
});

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

function render(catText: string, text = SITE_OFFICE) {
  const cat = loadCatalog(catText);
  if (!cat.ok) throw new Error(JSON.stringify(cat.errors));
  const layout = parseOffice(text, cat.value);
  if (!layout.ok) throw new Error(JSON.stringify(layout.errors));
  const map = buildWorldMap(layout.value, cat.value);
  if (!map.ok) throw new Error(JSON.stringify(map.errors));
  const r = renderMap(layout.value, map.value, cat.value);
  if (!r.ok) throw new Error(JSON.stringify(r.errors));
  return { map: r.value, layout: layout.value };
}

describe('каталог: anim у части и sounds у вида (спека фонтана 3)', () => {
  const m = (fn: (d: any) => void) => codes(mutateYaml(ANIM_CATALOG, fn));

  it('разбираются; без них вид прежний', () => {
    const c = loadCatalog(ANIM_CATALOG);
    if (!c.ok) throw new Error(JSON.stringify(c.errors));
    const bench = itemView(c.value.items['bench']!, null, 1);
    expect(bench.parts[0]!.anim).toEqual({ frames: 3, fps: 10 });
    expect(bench.sounds).toEqual([{ type: 'fountain', at: [8, 4] }]);
    const plain = loadCatalog(SITE_CATALOG);
    if (!plain.ok) throw new Error(JSON.stringify(plain.errors));
    expect(itemView(plain.value.items['bench']!, null, 1).sounds).toEqual([]);
    expect(itemView(plain.value.items['bench']!, null, 1).parts[0]!.anim).toBeUndefined();
  });

  it('форма — схема: frames ≥ 2, fps > 0, известный тип звука', () => {
    expect(m((d) => (d.items.bench.variants[0].default.parts[0].anim.frames = 1))).toEqual(['schema']);
    expect(m((d) => (d.items.bench.variants[0].default.parts[0].anim.fps = 0))).toEqual(['schema']);
    expect(m((d) => (d.items.bench.variants[0].default.sounds[0].type = 'river'))).toEqual(['schema']);
  });

  it('у декали петли и звука не бывает — ошибка, а не молчаливая потеря (как light_on_decal)', () => {
    expect(m((d) => (d.items.lane_dash.variants[0].default.parts[0].anim = { frames: 2, fps: 4 }))).toEqual(['anim_on_decal']);
    expect(m((d) => (d.items.lane_dash.variants[0].default.sounds = [{ type: 'fountain', at: [8, 8] }]))).toEqual(['sound_on_decal']);
  });
});

describe('renderMap: петля кадров и звуки на месте (спека фонтана 4)', () => {
  const { map, layout } = render(ANIM_CATALOG);

  it('кадры части — вправо от rect с шагом w; кадр 0 — frame спрайта', () => {
    const bench = map.sprites.find((s) => s.anim)!;
    expect(bench.anim!.fps).toBe(10);
    expect(bench.anim!.frames.map((f) => [f.x, f.y, f.w, f.h])).toEqual([[32, 192, 16, 16], [48, 192, 16, 16], [64, 192, 16, 16]]);
    expect(bench.anim!.frames[0]).toEqual(bench.frame);
    expect(map.sprites.filter((s) => s.anim)).toHaveLength(1);
  });

  it('звуки — мировые пиксели: клетка × ts + at, у предметов здания и участка', () => {
    const desk = layout.items.find((i) => i.item === 'desk')!;
    expect(map.sounds).toContainEqual({ type: 'fountain', x: desk.x * 16, y: desk.y * 16 - 2 });
    expect(map.sounds).toContainEqual({ type: 'fountain', x: 40, y: 148 }); // скамейка участка на клетке (2, 9)
    expect(map.sounds).toHaveLength(layout.items.filter((i) => i.item === 'desk').length + 1);
  });

  it('itemSounds — точка от левого верха предмета', () => {
    const c = loadCatalog(ANIM_CATALOG);
    if (!c.ok) throw new Error(JSON.stringify(c.errors));
    expect(itemSounds(itemView(c.value.items['bench']!, null, 1), 2, 3, 16)).toEqual([{ type: 'fountain', x: 40, y: 52 }]);
  });

  it('без anim и sounds — hello прежний', () => {
    const plain = render(SITE_CATALOG).map;
    expect(plain.sounds).toBeUndefined();
    expect(plain.sprites.some((s) => 'anim' in s)).toBe(false);
    expect(render(SITE_CATALOG, WORLD_OFFICE).map.sounds).toBeUndefined();
  });
});

describe('фонтан LimeZu (спека фонтана 3.3)', () => {
  const read = (rel: string) => readFileSync(new URL(rel, import.meta.url), 'utf8');
  const { map, layout } = render(read('../../../catalog/limezu/catalog.yaml'), read('../../../offices/demo/office.yaml'));

  it('8 кадров 32×48 по 10 в секунду и плеск в центре прямоугольника', () => {
    const f = layout.site!.items.find((i) => i.item === 'fountain')!;
    const sp = map.sprites.find((s) => s.anim && s.px === f.x * 16 && s.py === f.y * 16)!;
    expect(sp.anim!.fps).toBe(10);
    expect(sp.anim!.frames.map((fr) => fr.x)).toEqual([0, 32, 64, 96, 128, 160, 192, 224]);
    expect(sp.anim!.frames.every((fr) => fr.y === 0 && fr.w === 32 && fr.h === 48)).toBe(true);
    expect(map.sounds).toContainEqual({ type: 'fountain', x: f.x * 16 + 16, y: f.y * 16 + 24 });
  });
});
