import { mkdtempSync, readFileSync, utimesSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PNG } from 'pngjs';
import { describe, expect, it } from 'vitest';
import { ATLAS_LAYOUT, AtlasStore, ManualClock, OfficeHost, OfficeRuntime, VersionStore, atlasHash, collectFrames, frameKey, loadOffice, memoryLogger, packAtlas, renderAtlasPng, rewriteLayout, rewriteMap, rewriteVehicleKit, type SheetSource } from '../src/index.ts';
import type { Frame, Rect } from '@pixeloffice/protocol';
import { parse, stringify } from 'yaml';
import { demoOffice, miniAssets, patternPng } from './helpers.ts';
import { officeCopy } from './admin-helpers.ts';

describe('collectFrames (спека атласа 2.1)', () => {
  const office = demoOffice();
  const h = new OfficeRuntime({ office, clock: new ManualClock() }).hello();
  const frames = collectFrames(h.map, h.vehicleKit ?? null, h.characterLayout);
  const keys = new Set(frames.map(frameKey));
  const has = (f: Frame): boolean => keys.has(frameKey(f));

  it('карта: пол, спрайты с anim, двери, крыши, земля и полосы участка', () => {
    expect(h.map.floor.every((t) => has(t.frame))).toBe(true);
    expect(h.map.sprites.every((s) => has(s.frame) && (s.anim?.frames ?? [s.frame]).every(has))).toBe(true);
    expect(h.map.doors.every((d) => d.frames.every(has))).toBe(true);
    expect((h.map.roofs ?? []).every((r) => r.sprites.every((s) => has(s.frame)))).toBe(true);
    const site = h.map.site!;
    expect(site.ground.every((g) => g.frames.every(has))).toBe(true);
    expect(site.edges.every((e) => e.frames.every(has))).toBe(true);
  });

  it('транспорт: все направления всех моделей и автобус', () => {
    const kit = h.vehicleKit!;
    expect(kit.cars.every((c) => Object.values(c).every(has))).toBe(true);
    expect(has(kit.bus)).toBe(true);
  });

  it('облачка разговора: appear, tail, icons и sleep', () => {
    const e = h.characterLayout.talk!.emotes;
    const asFrame = (r: { x: number; y: number; w: number; h: number }): Frame => ({ sheet: e.sheet, x: r.x, y: r.y, w: r.w, h: r.h });
    expect(e.appear.every((r) => has(asFrame(r)))).toBe(true);
    expect(has(asFrame(e.tail))).toBe(true);
    expect(e.icons.every(([a, b]) => has(asFrame(a)) && has(asFrame(b)))).toBe(true);
    for (const r of e.sleep ?? []) expect(has(asFrame(r))).toBe(true);
  });

  it('дедуп по (sheet, x, y, w, h): повторяющийся тайл пола — один кадр', () => {
    expect(new Set(frames.map(frameKey)).size).toBe(frames.length);
    expect(frames.length).toBeLessThan(h.map.floor.length); // тайлы пола демо повторяются сотни раз
  });
});

describe('packAtlas (спека атласа 2.1.3)', () => {
  const f = (sheet: string, x: number, y: number, w: number, h: number): Frame => ({ sheet, x, y, w, h });

  it('кадры не пересекаются, между соседними 1 px, все в пределах страницы', () => {
    const frames = [f('a', 0, 0, 16, 16), f('a', 16, 0, 16, 16), f('b', 0, 0, 100, 8), f('b', 0, 8, 8, 40), f('c', 0, 0, 32, 32)];
    const { width, height, placed } = packAtlas(frames);
    const rects = frames.map((fr) => ({ ...placed.get(frameKey(fr))!, w: fr.w, h: fr.h }));
    for (const r of rects) {
      expect(r.x).toBeGreaterThanOrEqual(0);
      expect(r.y).toBeGreaterThanOrEqual(0);
      expect(r.x + r.w).toBeLessThanOrEqual(width);
      expect(r.y + r.h).toBeLessThanOrEqual(height);
    }
    // кадры, расширенные на 1 px, не пересекаются — это и есть зазор
    for (let i = 0; i < rects.length; i++)
      for (let j = i + 1; j < rects.length; j++) {
        const a = rects[i]!;
        const b = rects[j]!;
        const overlap = a.x < b.x + b.w + 1 && b.x < a.x + a.w + 1 && a.y < b.y + b.h + 1 && b.y < a.y + a.h + 1;
        expect(overlap, `кадры ${i} и ${j} ближе 1 px`).toBe(false);
      }
  });

  it('страница 1024; кадр шире расширяет её; пустой набор — пустая страница', () => {
    expect(packAtlas([f('a', 0, 0, 16, 16)]).width).toBe(1024);
    expect(packAtlas([f('a', 0, 0, 2000, 4)]).width).toBe(2000);
    expect([packAtlas([]).width, packAtlas([]).height]).toEqual([1024, 0]);
  });

  it('детерминирована: один набор — одна раскладка', () => {
    const frames = [f('a', 0, 0, 16, 16), f('a', 16, 0, 16, 8), f('b', 0, 0, 16, 16)];
    const p1 = packAtlas(frames);
    const p2 = packAtlas([...frames].reverse());
    const line = (p: typeof p1): string[] => [...p.placed.entries()].map(([k, v]) => `${k}:${v.x},${v.y}`).sort();
    expect(line(p1)).toEqual(line(p2));
  });
});

describe('rewrite* (спека атласа 2.3)', () => {
  const office = demoOffice();
  const h = new OfficeRuntime({ office, clock: new ManualClock() }).hello();
  const frames = collectFrames(h.map, h.vehicleKit ?? null, h.characterLayout);
  const { placed } = packAtlas(frames);
  const url = '/atlas/test-hash.png';
  const moved = (fr: Frame): Frame => {
    const at = placed.get(frameKey(fr))!;
    return { sheet: url, x: at.x, y: at.y, w: fr.w, h: fr.h };
  };

  it('rewriteMap: пол, спрайты с anim, двери, крыши, участок — координаты упаковки; прочее — те же ссылки', () => {
    const m = rewriteMap(h.map, url, placed);
    h.map.floor.forEach((t, i) => expect(m.floor[i]!.frame).toEqual(moved(t.frame)));
    h.map.sprites.forEach((s, i) => {
      expect(m.sprites[i]!.frame).toEqual(moved(s.frame));
      (s.anim?.frames ?? []).forEach((a, k) => expect(m.sprites[i]!.anim!.frames[k]).toEqual(moved(a)));
      expect(m.sprites[i]!.px).toBe(s.px); // не-кадровые поля копируются как есть
    });
    h.map.doors.forEach((d, i) => d.frames.forEach((a, k) => expect(m.doors[i]!.frames[k]).toEqual(moved(a))));
    (h.map.roofs ?? []).forEach((r, i) => r.sprites.forEach((s, k) => expect(m.roofs![i]!.sprites[k]!.frame).toEqual(moved(s.frame))));
    const site = h.map.site!;
    site.ground.forEach((g, i) => g.frames.forEach((a, k) => expect(m.site!.ground[i]!.frames[k]).toEqual(moved(a))));
    site.edges.forEach((e, i) => e.frames.forEach((a, k) => expect(m.site!.edges[i]!.frames[k]).toEqual(moved(a))));
    expect(m.spots).toBe(h.map.spots);
    expect(m.screenArt).toBe(h.map.screenArt);
  });

  it('rewriteVehicleKit: кадры всех направлений и автобус; lift и engines — прежние', () => {
    const k = rewriteVehicleKit(h.vehicleKit!, url, placed);
    h.vehicleKit!.cars.forEach((c, i) => {
      for (const d of ['up', 'down', 'left', 'right'] as const) expect(k.cars[i]![d]).toEqual(moved(c[d]));
    });
    expect(k.bus).toEqual(moved(h.vehicleKit!.bus));
    expect(k.busLift).toBe(h.vehicleKit!.busLift);
    expect(k.carLift).toBe(h.vehicleKit!.carLift);
    expect(k.engines).toBe(h.vehicleKit!.engines);
  });

  it('rewriteLayout: emotes — URL атласа и координаты упаковки; animations — тот же объект', () => {
    const l = rewriteLayout(h.characterLayout, url, placed);
    const e = h.characterLayout.talk!.emotes;
    const ne = l.talk!.emotes;
    expect(ne.sheet).toBe(url);
    const mv = (r: Rect): Rect => {
      const at = placed.get(frameKey({ sheet: e.sheet, x: r.x, y: r.y, w: r.w, h: r.h }))!;
      return { x: at.x, y: at.y, w: r.w, h: r.h };
    };
    expect(ne.appear).toEqual(e.appear.map(mv));
    expect(ne.tail).toEqual(mv(e.tail));
    expect(ne.icons).toEqual(e.icons.map(([a, b]) => [mv(a), mv(b)]));
    expect(l.animations).toBe(h.characterLayout.animations); // не кадры — те же объекты
    expect(l.talk!.speakers).toBe(h.characterLayout.talk!.speakers);
  });
});

describe('renderAtlasPng (спека атласа 2.1.4)', () => {
  it('кадр за краем листа: пиксели внутри — из листа, за краем — прозрачные', async () => {
    const src = patternPng(4, 4, 7); // лист 4×4
    const f: Frame = { sheet: '/sprites/s.png', x: 2, y: 2, w: 4, h: 4 }; // торчит за правый и нижний край
    const { width, height, placed } = packAtlas([f]);
    const png = await renderAtlasPng([f], placed, width, height, { get: async () => src });
    const at = placed.get(frameKey(f))!;
    const px = (x: number, y: number): number[] => {
      const i = ((at.y + y) * width + at.x + x) * 4;
      return [...png.data.subarray(i, i + 4)];
    };
    const srcPx = (x: number, y: number): number[] => {
      const i = (y * src.width + x) * 4;
      return [...src.data.subarray(i, i + 4)];
    };
    expect(px(0, 0)).toEqual(srcPx(2, 2)); // левый верх кадра — из листа
    expect(px(1, 1)).toEqual(srcPx(3, 3));
    expect(px(2, 0)).toEqual([0, 0, 0, 0]); // за правым краем листа
    expect(px(0, 2)).toEqual([0, 0, 0, 0]); // за нижним краем листа
    expect(px(3, 3)).toEqual([0, 0, 0, 0]); // за обоими
  });
});

describe('AtlasStore (спека атласа 2.2)', () => {
  const office = demoOffice();
  const h = new OfficeRuntime({ office, clock: new ManualClock() }).hello();
  const frames = collectFrames(h.map, h.vehicleKit ?? null, h.characterLayout);

  const dataDir = (): string => mkdtempSync(join(tmpdir(), 'po-atlas-data-'));
  const store = (assets: string, sheets: SheetSource): { store: AtlasStore; dataDir: string } => {
    const dir = dataDir();
    return { store: new AtlasStore({ dataDir: dir, assetsDir: assets, catalog: office.bundle.catalog, sheets }), dataDir: dir };
  };

  it('get: план с URL /atlas/<hash>.png, PNG на диске повторяет исходники попиксельно', async () => {
    const { assets, sheets } = miniAssets(office.bundle.catalog, frames);
    const { store: s } = store(assets, sheets);
    const plan = await s.get(frames);
    expect(plan).not.toBeNull();
    expect(plan!.url).toMatch(/^\/atlas\/[0-9a-f]{64}\.png$/);
    const body = await s.read(plan!.url.slice('/atlas/'.length, -'.png'.length));
    const png = PNG.sync.read(body!);
    for (const f of frames) {
      const at = plan!.rects.get(frameKey(f))!;
      const src = await sheets.get(f.sheet);
      let same = true;
      for (let y = 0; y < f.h && same; y++) {
        const from = ((f.y + y) * src.width + f.x) * 4;
        const to = ((at.y + y) * png.width + at.x) * 4;
        same = png.data.subarray(to, to + f.w * 4).equals(src.data.subarray(from, from + f.w * 4));
      }
      expect(same, frameKey(f)).toBe(true);
    }
  });

  // Две паковки демо-набора в файле + мини-ассеты на диск: под нагрузкой воркеров дефолтных 5 с не хватает.
  it('файл есть — не перепаковываем: тот же store (кеш в памяти) и новый после рестарта', { timeout: 20_000 }, async () => {
    const { assets, sheets } = miniAssets(office.bundle.catalog, frames);
    const { store: s, dataDir: dir } = store(assets, sheets);
    const plan = (await s.get(frames))!;
    const file = join(dir, 'atlas', plan.url.slice('/atlas/'.length));
    writeFileSync(file, 'маркер'); // если перепакует — маркер затрётся
    expect((await s.get(frames))!.url).toBe(plan.url); // промис из кеша в памяти
    const restarted = new AtlasStore({ dataDir: dir, assetsDir: assets, catalog: office.bundle.catalog, sheets });
    expect((await restarted.get(frames))!.url).toBe(plan.url); // файл на диске есть
    expect(readFileSync(file, 'utf8')).toBe('маркер');
  });

  it('версия раскладки в ключе: правка упаковщика меняет hash (спека атласа 2.2.1)', () => {
    const f: Frame = { sheet: '/sprites/a.png', x: 0, y: 0, w: 16, h: 16 };
    const meta = new Map([['/sprites/a.png', { size: 100, mtimeMs: 1 }]]);
    expect(atlasHash([f], meta)).toBe(atlasHash([f], meta, ATLAS_LAYOUT)); // дефолт — текущая версия раскладки
    expect(atlasHash([f], meta, ATLAS_LAYOUT + 1)).not.toBe(atlasHash([f], meta)); // правка packAtlas — новый ключ, старый PNG не подойдёт
  });

  // Три полных паковки набора demo: под нагрузкой параллельных воркеров витеста 5 с дефолта не хватает
  // (flake ловился серийными прогонами), логика теста не меняется — только лимит времени.
  it('правка листа меняет hash: и mtime, и байтовый размер (спека атласа 2.2.1)', { timeout: 20_000 }, async () => {
    const { assets, sheets } = miniAssets(office.bundle.catalog, frames);
    const { store: s } = store(assets, sheets);
    const url1 = (await s.get(frames))!.url;
    const someSheet = join(assets, frames[0]!.sheet.slice('/sprites/'.length));
    utimesSync(someSheet, new Date(), new Date(Date.now() + 5000)); // правка пикселей без смены размеров ловится mtime
    const url2 = (await s.get(frames))!.url;
    expect(url2).not.toBe(url1);
    const old = PNG.sync.read(readFileSync(someSheet));
    writeFileSync(someSheet, PNG.sync.write(new PNG({ width: old.width + 1, height: old.height }))); // другой размер файла
    const url3 = (await s.get(frames))!.url;
    expect(url3).not.toBe(url2);
  });

  it('лист не читается — null и предупреждение в журнал (спека атласа 2.4.1)', async () => {
    const { assets } = miniAssets(office.bundle.catalog, frames);
    const log = memoryLogger();
    const s = new AtlasStore({ dataDir: dataDir(), assetsDir: assets, catalog: office.bundle.catalog, sheets: { get: async () => { throw new Error('битый лист'); } }, log });
    expect(await s.get(frames)).toBeNull();
    expect(log.lines.some((l) => l.level === 'warn' && l.msg.includes('атлас'))).toBe(true);
  });

  it('листа нет на диске — null: stat до паковки', async () => {
    const empty = mkdtempSync(join(tmpdir(), 'po-atlas-empty-'));
    const { sheets } = miniAssets(office.bundle.catalog, frames);
    const s = new AtlasStore({ dataDir: dataDir(), assetsDir: empty, catalog: office.bundle.catalog, sheets });
    expect(await s.get(frames)).toBeNull();
  });

  it('пустой набор — null; read чужого hash — null', async () => {
    const { assets, sheets } = miniAssets(office.bundle.catalog, frames);
    const { store: s } = store(assets, sheets);
    expect(await s.get([])).toBeNull();
    expect(await s.read('0'.repeat(64))).toBeNull();
    expect(await s.read('../../etc/passwd')).toBeNull();
  });
});

describe('OfficeRuntime с атласом (спека атласа 2.3, 2.5.1)', () => {
  const office = demoOffice();
  const plain = new OfficeRuntime({ office, clock: new ManualClock() }).hello();
  const frames = collectFrames(plain.map, plain.vehicleKit ?? null, plain.characterLayout);
  const { assets, sheets } = miniAssets(office.bundle.catalog, frames);

  it('hello — атласные копии всех трёх частей; до готовности и без атласа — исходные листы', async () => {
    const store = new AtlasStore({ dataDir: mkdtempSync(join(tmpdir(), 'po-atlas-rt-')), assetsDir: assets, catalog: office.bundle.catalog, sheets });
    const rt = new OfficeRuntime({ office, clock: new ManualClock(), atlas: store });
    expect(rt.hello().map.floor[0]!.frame.sheet).toMatch(/^\/sprites\//); // паковка ещё идёт — исходные URL (спека 2.3.3)
    await rt.ready();
    const h = rt.hello();
    const url = h.map.floor[0]!.frame.sheet;
    expect(url).toMatch(/^\/atlas\/[0-9a-f]{64}\.png$/);
    for (const t of h.map.floor) expect(t.frame.sheet).toBe(url);
    for (const s of h.map.sprites) expect(s.frame.sheet).toBe(url);
    expect(h.characterLayout.talk!.emotes.sheet).toBe(url);
    expect(h.vehicleKit!.bus.sheet).toBe(url);
    expect(h.vehicleKit!.cars.every((c) => Object.values(c).every((f) => f.sheet === url))).toBe(true);
    // исходный бандл не тронут (office и так заморожен deepFreeze — мутация бы упала)
    expect(office.bundle.rendered.floor[0]!.frame.sheet).toMatch(/^\/sprites\//);
    // повторные hello дешёвые: копии не пересобираются (спека 2.3.1)
    expect(rt.hello().map).toBe(h.map);
    expect(rt.hello().characterLayout).toBe(h.characterLayout);
  });

  it('паковка не удалась — hello на исходных листах, ready() не бросает (спека атласа 2.4.1)', async () => {
    const log = memoryLogger();
    const bad = new AtlasStore({ dataDir: mkdtempSync(join(tmpdir(), 'po-atlas-rt-')), assetsDir: assets, catalog: office.bundle.catalog, sheets: { get: async () => { throw new Error('упал'); } }, log });
    const rt = new OfficeRuntime({ office, clock: new ManualClock(), atlas: bad, log });
    await expect(rt.ready()).resolves.toBeUndefined();
    expect(rt.hello().map.floor[0]!.frame.sheet).toMatch(/^\/sprites\//);
    expect(log.lines.some((l) => l.level === 'warn' && l.msg.includes('атлас'))).toBe(true);
  });

  it('без атласа (CI, нет assetsDir) — hello как раньше', () => {
    const rt = new OfficeRuntime({ office, clock: new ManualClock() });
    expect(rt.hello().map.floor[0]!.frame.sheet).toMatch(/^\/sprites\//);
    expect(rt.hello().characterLayout.talk!.emotes.sheet).toMatch(/^\/sprites\//);
  });
});

describe('OfficeHost с атласом (спека атласа 2.4.3)', () => {
  it('apply: атлас нового runtime готов до отключения зрителей; тот же набор кадров — тот же hash', async () => {
    const { dir } = officeCopy();
    const office = loadOffice(dir);
    const clock = new ManualClock();
    const plain = new OfficeRuntime({ office, clock: new ManualClock() }).hello();
    const frames = collectFrames(plain.map, plain.vehicleKit ?? null, plain.characterLayout);
    const { assets, sheets } = miniAssets(office.bundle.catalog, frames);
    const store = new AtlasStore({ dataDir: office.dataDir, assetsDir: assets, catalog: office.bundle.catalog, sheets });
    const host = new OfficeHost({ office, clock, log: memoryLogger(), versions: new VersionStore(office.dataDir, clock), atlas: store });
    // В момент отключения зрителей (onReset) hello уже атласный — это и есть «готовность до onReset» (спека 2.4.3).
    const resets: boolean[] = [];
    host.onReset = () => resets.push(host.runtime.hello().map.floor[0]!.frame.sheet.startsWith('/atlas/'));
    await host.runtime.ready();
    const url = host.runtime.hello().map.floor[0]!.frame.sheet;
    expect(url).toMatch(/^\/atlas\//);
    const people = host.current().files['people.yaml']!;
    const swapped = stringify({ people: (parse(people) as { people: { id: string; pod: string }[] }).people.map((p) => (p.id === 'p1' ? { ...p, pod: 'pod:p6' } : p.id === 'p6' ? { ...p, pod: 'pod:p1' } : p)) });
    const r = await host.apply({ 'people.yaml': swapped }, { comment: 'сменить кабинки' });
    expect(r.status).toBe('applied');
    expect(resets).toEqual([true]);
    // набор кадров не изменился — тот же hash, файл уже на диске, пересборка мгновенная (спека 2.4.3)
    expect(host.runtime.hello().map.floor[0]!.frame.sheet).toBe(url);
  });
});
