import { existsSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { PNG } from 'pngjs';
import { describe, expect, it } from 'vitest';
import { PREVIEW_COLORS, PREVIEW_MARGIN, SheetCache, previewBounds, previewLegend, renderPreview } from '../src/index.ts';
import { demoOffice } from './helpers.ts';

// Пустые листы: картинка без арта, но с теми же размерами, рамками зон и точками мест.
const blank = { get: async () => new PNG({ width: 1, height: 1 }) };
const pixel = (png: PNG, x: number, y: number) => [...png.data.subarray((y * png.width + x) * 4, (y * png.width + x) * 4 + 4)];

describe('renderPreview (спека хостинга 7.2)', () => {
  it('plain — по границам мира, grid — больше на поля подписей', async () => {
    const b = demoOffice().bundle;
    const { plain, grid } = await renderPreview(b, blank);
    const p = PNG.sync.read(plain);
    const g = PNG.sync.read(grid);
    const bb = previewBounds(b.rendered);
    expect([p.width, p.height]).toEqual([bb.maxX - bb.minX, bb.maxY - bb.minY]);
    expect([g.width, g.height]).toEqual([p.width + 2 * PREVIEW_MARGIN.frame + PREVIEW_MARGIN.axisX, p.height + 2 * PREVIEW_MARGIN.frame + PREVIEW_MARGIN.axisY]);
    const site = b.layout.site!.rect;
    expect(bb.minX).toBeLessThanOrEqual(site[0] * 16);
    expect(bb.maxX).toBeGreaterThanOrEqual((site[0] + site[2]) * 16);
  });

  it('grid: рамка зоны цветом вида, точка места цветом вида места', async () => {
    const b = demoOffice().bundle;
    const g = PNG.sync.read((await renderPreview(b, blank)).grid);
    const bb = previewBounds(b.rendered);
    const sx = (wx: number) => wx - bb.minX + PREVIEW_MARGIN.frame + PREVIEW_MARGIN.axisX;
    const sy = (wy: number) => wy - bb.minY + PREVIEW_MARGIN.frame + PREVIEW_MARGIN.axisY;
    const zone = b.layout.zones.find((z) => z.id === 'pod:p1')!;
    // Левый верхний угол рамки — на 1 px правее и ниже линии сетки, чтобы сетка его не перекрыла.
    expect(pixel(g, sx(zone.rect[0] * 16) + 1, sy(zone.rect[1] * 16) + 1)).toEqual(PREVIEW_COLORS.zone.pod);
    const seat = b.map.spotsInZone('pod:p1').find((s) => s.tags.includes('owner_seat'))!;
    expect(pixel(g, sx(seat.x * 16 + 8), sy(seat.y * 16 + 8))).toEqual(PREVIEW_COLORS.spot.work);
  });

  it('легенда называет все цвета', () => {
    const md = previewLegend();
    for (const k of ['pod', 'meeting', 'common']) expect(md).toContain(k);
    expect(md).toContain('портал');
  });

  const ASSETS = join(homedir(), 'tmp');
  it.skipIf(!existsSync(ASSETS))('на настоящих листах LimeZu собирается без ошибок', async () => {
    const b = demoOffice().bundle;
    const first = Object.values(b.catalog.sheets)[0]!;
    if (!existsSync(join(ASSETS, first))) return; // пака нет — как у остальных тестов атласа
    const { plain } = await renderPreview(b, new SheetCache(ASSETS, b.catalog));
    expect(PNG.sync.read(plain).width).toBeGreaterThan(0);
  }, 20_000); // декодирует настоящие листы пака: ~1 с на свободной машине, под нагрузкой gate — в разы дольше
});
