import { mkdtempSync } from 'node:fs';
import type { AddressInfo } from 'node:net';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { PNG } from 'pngjs';
import { afterEach, describe, expect, it } from 'vitest';
import type { HelloMessage, ServerMessage } from '@pixeloffice/protocol';
import { AtlasStore, ManualClock, OfficeRuntime, buildServer, collectFrames, renderScenario } from '../src/index.ts';
import { demoOffice, miniAssets } from './helpers.ts';

const TOKEN = 'demo-viewer-token';
const closers: (() => Promise<unknown>)[] = [];
afterEach(async () => {
  while (closers.length) await closers.pop()!();
});

const office = demoOffice();
const plain = new OfficeRuntime({ office, clock: new ManualClock() }).hello();
const frames = collectFrames(plain.map, plain.vehicleKit ?? null, plain.characterLayout);

async function start() {
  const { assets, sheets } = miniAssets(office.bundle.catalog, frames);
  const atlas = new AtlasStore({ dataDir: mkdtempSync(join(tmpdir(), 'po-atlas-http-')), assetsDir: assets, catalog: office.bundle.catalog, sheets });
  const rt = new OfficeRuntime({ office, clock: new ManualClock(), atlas });
  await rt.ready();
  const srv = await buildServer({ runtime: rt, viewerTokens: [TOKEN], assetsDir: assets, viewerDist: null, atlas, testMode: (q) => renderScenario(office, q, { atlas }) });
  await srv.app.listen({ port: 0, host: '127.0.0.1' });
  closers.push(() => srv.app.close());
  return { rt, srv, base: `http://127.0.0.1:${(srv.app.server.address() as AddressInfo).port}` };
}

// Каждый тест поднимает сервер с полной паковкой атласа демо-набора (мини-ассеты пишутся на диск и пакуются);
// под нагрузкой параллельных воркеров витеста 5 с дефолта не хватает (flake ловился серийными прогонами) —
// лимит файла целиком, логика тестов не меняется.
describe('мини-атлас: hello и отдача (спека атласа 2.2.3, 2.3)', { timeout: 30_000 }, () => {
  it('hello демо ссылается на /atlas/<hash>.png; маршрут отдаёт PNG с private immutable', async () => {
    const s = await start();
    const url = s.rt.hello().map.floor[0]!.frame.sheet;
    expect(url).toMatch(/^\/atlas\/[0-9a-f]{64}\.png$/);
    const res = await s.srv.app.inject({ method: 'GET', url: `${url}?token=${TOKEN}` });
    expect(res.statusCode).toBe(200);
    expect(res.headers['content-type']).toBe('image/png');
    expect(res.headers['cache-control']).toBe('private, max-age=31536000, immutable');
    expect(PNG.sync.read(res.rawPayload).width).toBeGreaterThan(0);
  });

  it('без токена — 401; чужой hash — 404', async () => {
    const s = await start();
    const url = s.rt.hello().map.floor[0]!.frame.sheet;
    expect((await s.srv.app.inject({ method: 'GET', url })).statusCode).toBe(401);
    expect((await s.srv.app.inject({ method: 'GET', url: `/atlas/${'0'.repeat(64)}.png?token=${TOKEN}` })).statusCode).toBe(404);
  });

  it('тестовый режим: hello сценария — атласный (testMode асинхронный, ждёт готовности)', async () => {
    const s = await start();
    const got: ServerMessage[] = [];
    const ws = new WebSocket(`${s.base.replace('http', 'ws')}/v1/ws?token=${TOKEN}&scenario=morning&t=0&seed=1`);
    closers.push(async () => ws.close());
    ws.addEventListener('message', (e) => got.push(JSON.parse(String(e.data))));
    await new Promise((r) => setTimeout(r, 500));
    const hello = got.find((m) => m.type === 'hello') as HelloMessage | undefined;
    expect(hello?.map.floor[0]!.frame.sheet).toMatch(/^\/atlas\//);
  });

  it('без assetsDir (CI) — hello на исходных листах, маршрута /atlas нет', async () => {
    const rt = new OfficeRuntime({ office, clock: new ManualClock() });
    expect(rt.hello().map.floor[0]!.frame.sheet).toMatch(/^\/sprites\//);
    const srv = await buildServer({ runtime: rt, viewerTokens: [TOKEN], assetsDir: null, viewerDist: null, testMode: null });
    closers.push(() => srv.app.close());
    expect((await srv.app.inject({ method: 'GET', url: `/atlas/${'0'.repeat(64)}.png?token=${TOKEN}` })).statusCode).toBe(404);
  });
});
