import { createHash, randomBytes } from 'node:crypto';
import { existsSync } from 'node:fs';
import { mkdir, readFile, rename, stat, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { PNG } from 'pngjs';
import type { Catalog } from '@pixeloffice/core';
import type { CharacterLayout, Facing, Frame, MapSprite, Rect, RenderedMap, VehicleKit } from '@pixeloffice/protocol';
import type { Logger } from './logger.ts';
import type { SheetSource } from './preview.ts';

// Ключ кадра атласа (спека атласа 2.1.2): дедуп по (sheet, x, y, w, h).
export const frameKey = (f: Frame): string => `${f.sheet}|${f.x},${f.y},${f.w},${f.h}`;

const rectFrame = (sheet: string, r: { x: number; y: number; w: number; h: number }): Frame => ({ sheet, x: r.x, y: r.y, w: r.w, h: r.h });

// Все кадры одного hello (спека атласа 2.1.1): карта (пол, спрайты с anim, двери, крыши, земля и полосы
// участка), транспорт и облачка разговора. Дедуп по frameKey: тайл пола повторяется сотни раз — в атласе один.
export function collectFrames(map: RenderedMap, kit: VehicleKit | null, layout: CharacterLayout | null): Frame[] {
  const out = new Map<string, Frame>();
  const add = (f: Frame): void => void out.set(frameKey(f), f);
  const addSprite = (s: { frame: Frame; anim?: { frames: Frame[] } }): void => {
    add(s.frame);
    for (const f of s.anim?.frames ?? []) add(f);
  };
  for (const t of map.floor) add(t.frame);
  for (const s of map.sprites) addSprite(s);
  for (const d of map.doors) for (const f of d.frames) add(f);
  for (const r of map.roofs ?? []) for (const s of r.sprites) addSprite(s);
  if (map.site) {
    for (const g of map.site.ground) for (const f of g.frames) add(f);
    for (const e of map.site.edges) for (const f of e.frames) add(f);
  }
  if (kit) {
    for (const car of kit.cars) for (const f of Object.values(car)) add(f);
    add(kit.bus);
  }
  const e = layout?.talk?.emotes;
  if (e) {
    for (const r of e.appear) add(rectFrame(e.sheet, r));
    add(rectFrame(e.sheet, e.tail));
    for (const pair of e.icons) for (const r of pair) add(rectFrame(e.sheet, r));
    for (const r of e.sleep ?? []) add(rectFrame(e.sheet, r));
  }
  return [...out.values()];
}

// Ширина страницы атласа (спека атласа 2.1.3): 1024 px.
export const ATLAS_WIDTH = 1024;

// Версия раскладки упаковщика (в ключе кеша, спека атласа 2.2.1): любая правка packAtlas — ширина, зазор, порядок
// полок, tie-break — поднимает её. Иначе при неизменном арте hash остался бы прежним, и build подложил бы старый
// PNG на диске под новые координаты раскладки, а immutable-заголовок закрепил бы расхождение в кешах зрителей.
export const ATLAS_LAYOUT = 1;

// Куда лёг кадр в атласе.
export type Placed = { x: number; y: number };

// Shelf-упаковка (спека атласа 2.1.3): полки по убыванию высоты кадра, между соседними кадрами 1 px прозрачного
// зазора — при дробном масштабе (вписывание при открытии, ступени зума) nearest-фильтр без зазора тянет пиксель
// соседнего кадра. Вторая страница не заводится: лимита карты 150×100 клеток хватает с запасом; кадр шире
// страницы расширяет её. Чистая и детерминированная: один набор — одна раскладка (tie-break по frameKey).
export function packAtlas(frames: Frame[]): { width: number; height: number; placed: Map<string, Placed> } {
  const list = [...frames].sort((a, b) => b.h - a.h || b.w - a.w || frameKey(a).localeCompare(frameKey(b)));
  const width = Math.max(ATLAS_WIDTH, ...list.map((fr) => fr.w));
  const placed = new Map<string, Placed>();
  let x = 0;
  let y = 0;
  let shelfH = 0;
  for (const fr of list) {
    if (x + fr.w > width) {
      x = 0;
      y += shelfH + 1;
      shelfH = 0;
    }
    placed.set(frameKey(fr), { x, y });
    x += fr.w + 1;
    shelfH = Math.max(shelfH, fr.h);
  }
  return { width, height: list.length ? y + shelfH : 0, placed };
}

// Переписывание hello на атлас (спека атласа 2.3): копии с URL /atlas/<hash>.png и координатами упаковки;
// URL без хоста — как у /sprites/..., вьюер за прокси резолвит сам (спека 2.3.4). Исходные объекты не мутируются
// (предпросмотр и SheetCache живут по старым путям). Кадр вне placed — недостижимая по построению ветка
// (все источники кадров перечислены в collectFrames) — остался бы исходным.
const rewriteFrame = (f: Frame, url: string, placed: Map<string, Placed>): Frame => {
  const at = placed.get(frameKey(f));
  return at ? { sheet: url, x: at.x, y: at.y, w: f.w, h: f.h } : f;
};

export function rewriteMap(map: RenderedMap, url: string, placed: Map<string, Placed>): RenderedMap {
  const frame = (f: Frame): Frame => rewriteFrame(f, url, placed);
  const sprite = (s: MapSprite): MapSprite => ({ ...s, frame: frame(s.frame), ...(s.anim ? { anim: { ...s.anim, frames: s.anim.frames.map(frame) } } : {}) });
  return {
    ...map,
    floor: map.floor.map((t) => ({ ...t, frame: frame(t.frame) })),
    sprites: map.sprites.map(sprite),
    doors: map.doors.map((d) => ({ ...d, frames: d.frames.map(frame) })),
    ...(map.roofs ? { roofs: map.roofs.map((r) => ({ ...r, sprites: r.sprites.map(sprite) })) } : {}),
    ...(map.site
      ? {
          site: {
            ...map.site,
            ground: map.site.ground.map((g) => ({ ...g, frames: g.frames.map(frame) })),
            edges: map.site.edges.map((e) => ({ ...e, frames: e.frames.map(frame) })),
          },
        }
      : {}),
  };
}

export function rewriteVehicleKit(kit: VehicleKit, url: string, placed: Map<string, Placed>): VehicleKit {
  const frame = (f: Frame): Frame => rewriteFrame(f, url, placed);
  return {
    ...kit,
    cars: kit.cars.map((c) => Object.fromEntries(Object.entries(c).map(([d, f]) => [d, frame(f)])) as Record<Facing, Frame>),
    bus: frame(kit.bus),
  };
}

export function rewriteLayout(layout: CharacterLayout, url: string, placed: Map<string, Placed>): CharacterLayout {
  const t = layout.talk;
  if (!t) return layout;
  const move = (r: Rect): Rect => {
    const at = placed.get(frameKey({ sheet: t.emotes.sheet, x: r.x, y: r.y, w: r.w, h: r.h }));
    return at ? { ...r, x: at.x, y: at.y } : r;
  };
  return {
    ...layout,
    talk: {
      ...t,
      emotes: {
        ...t.emotes,
        sheet: url,
        appear: t.emotes.appear.map(move),
        tail: move(t.emotes.tail),
        icons: t.emotes.icons.map(([a, b]) => [move(a), move(b)]),
        ...(t.emotes.sleep ? { sleep: t.emotes.sleep.map(move) as [Rect, Rect] } : {}),
      },
    },
  };
}

// sha256 набора (спека атласа 2.2.1): по отсортированным кадрам и метаданным листов — байтовому размеру и mtime.
// 32-битного FNV-1a мало: коллизия подложила бы чужой атлас под неизменный immutable-URL; правка пикселей без
// смены размеров ни набор кадров, ни размеры листов не меняют — их ловят размер файла и mtime (pnpm art,
// обновление пака на месте). layout — версия раскладки: входит в ключ, правка упаковщика меняет все hash разом.
export function atlasHash(frames: Frame[], sheetMeta: Map<string, { size: number; mtimeMs: number }>, layout: number = ATLAS_LAYOUT): string {
  const key = JSON.stringify([
    layout,
    [...frames].map(frameKey).sort(),
    [...sheetMeta.entries()].map(([s, m]) => [s, m.size, m.mtimeMs]).sort(([a], [b]) => (a < b ? -1 : 1)),
  ]);
  return createHash('sha256').update(key).digest('hex');
}

// Сборка PNG атласа (спека атласа 2.1.4): кадры копируются с исходных листов через SheetCache (он уже кеширует
// декодированные листы в памяти процесса); пиксели за краем листа — прозрачные, как в предпросмотре.
export async function renderAtlasPng(
  frames: Frame[],
  placed: Map<string, Placed>,
  width: number,
  height: number,
  sheets: SheetSource,
): Promise<PNG> {
  const png = new PNG({ width, height });
  const bySheet = new Map<string, Frame[]>();
  for (const f of frames) bySheet.set(f.sheet, [...(bySheet.get(f.sheet) ?? []), f]);
  // Прогрев параллельно (SheetCache дедупит промисы по имени): чтение и декодирование листов не выстраиваются
  // в очередь за копированием кадров предыдущего — холодная паковка короче, а с ней и окно apply при смене арта.
  await Promise.all([...bySheet.keys()].map((s) => sheets.get(s)));
  for (const [sheet, list] of bySheet) {
    const src = await sheets.get(sheet); // промис прогрет — берём без паузы
    for (const f of list) {
      const at = placed.get(frameKey(f))!;
      // Строка кадра переносится одним куском: сколько её пикселей в листе, столько и копируем, хвост за правым
      // краем остаётся прозрачным. Строки ниже листа — прозрачные целиком.
      const inRow = Math.min(f.w, Math.max(0, src.width - f.x));
      for (let y = 0; y < f.h; y++) {
        const fy = f.y + y;
        if (fy >= src.height) break;
        const from = (fy * src.width + f.x) * 4;
        const to = ((at.y + y) * width + at.x) * 4;
        png.data.set(src.data.subarray(from, from + inRow * 4), to);
      }
    }
  }
  return png;
}

// Путь листа в assetsDir: кадры hello несут URL /sprites/...; имя листа каталога — как в SheetCache. Имена листов
// всех паков — ASCII: URL с %XX (пробел или кириллица в имени файла) попал бы сюда не декодированным, и атлас, как
// и предпросмотр с тем же срезом, молча ушёл бы на исходные листы — осознанное ограничение до не-ASCII листов.
export function sheetRel(sheet: string, catalog: Catalog): string | null {
  if (sheet.startsWith('/sprites/')) return sheet.slice('/sprites/'.length);
  return catalog.sheets[sheet] ?? null;
}

export type AtlasPlan = { url: string; rects: Map<string, Placed> }; // поле rects — имя контракта из спеки атласа 2.5.1
export type AtlasOptions = { dataDir: string; assetsDir: string; catalog: Catalog; sheets: SheetSource; log?: Logger };

// Хранилище мини-атласов (спека атласа 2.2, 2.5.1): кеш в памяти — промис на hash (параллельные паковки одного
// набора не дублируются), на диске — <dataDir>/atlas/<hash>.png с атомарной записью (временный файл + rename —
// обрыв записи не оставит битый PNG под верным именем). Старые файлы не чистятся: их единицы, лежат в dataDir,
// чистка — гонки с concurrent-запросом; лишнее стирается вручную вместе с dataDir (спека 2.2.4).
export class AtlasStore {
  private readonly dir: string;
  private readonly o: AtlasOptions;
  private readonly cache = new Map<string, Promise<AtlasPlan | null>>();

  constructor(o: AtlasOptions) {
    this.o = o;
    this.dir = join(o.dataDir, 'atlas');
  }

  // Паковка набора кадров hello: null — не удалась (листа нет, pngjs упал) — hello остаётся на исходных листах.
  // Неудача кешируется до конца процесса: набор и метаданные листов не изменились бы, повтор в том же процессе
  // дал бы тот же результат; правка листа меняет hash — новым ключом кеша.
  get(frames: Frame[]): Promise<AtlasPlan | null> {
    if (frames.length === 0) return Promise.resolve(null);
    return this.hashOf(frames)
      .then((hash) => {
        let p = this.cache.get(hash);
        if (!p) {
          p = this.build(frames, hash).catch((e: unknown) => {
            this.o.log?.warn(`атлас не собран: ${(e as Error).message}`);
            return null;
          });
          this.cache.set(hash, p);
        }
        return p;
      })
      .catch((e: unknown) => {
        this.o.log?.warn(`атлас не собран: ${(e as Error).message}`);
        return null;
      });
  }

  // Тело атласа для маршрута /atlas/:hash.png (спека атласа 2.2.3): с диска при запросе, дальше решает
  // браузерный кеш. Имя файла — hex sha256, отдаём только существующие.
  async read(hash: string): Promise<Buffer | null> {
    if (!/^[0-9a-f]{64}$/.test(hash)) return null;
    try {
      return await readFile(join(this.dir, `${hash}.png`));
    } catch {
      return null;
    }
  }

  // sha256 набора с метаданными листов: stat каждого листа, без чтения содержимого.
  private async hashOf(frames: Frame[]): Promise<string> {
    const meta = new Map<string, { size: number; mtimeMs: number }>();
    for (const sheet of new Set(frames.map((f) => f.sheet))) {
      const rel = sheetRel(sheet, this.o.catalog);
      if (!rel) throw new Error(`лист «${sheet}» не найден в каталоге`);
      const st = await stat(join(this.o.assetsDir, rel));
      meta.set(sheet, { size: st.size, mtimeMs: st.mtimeMs });
    }
    return atlasHash(frames, meta);
  }

  private async build(frames: Frame[], hash: string): Promise<AtlasPlan> {
    const { width, height, placed } = packAtlas(frames); // раскладка детерминирована — файлу соответствует
    const file = join(this.dir, `${hash}.png`);
    if (!existsSync(file)) {
      const png = await renderAtlasPng(frames, placed, width, height, this.o.sheets);
      await mkdir(this.dir, { recursive: true });
      const tmp = join(this.dir, `.${hash}.${randomBytes(4).toString('hex')}.tmp`);
      await writeFile(tmp, PNG.sync.write(png));
      await rename(tmp, file);
    }
    return { url: `/atlas/${hash}.png`, rects: placed };
  }
}
