import { createReadStream } from 'node:fs';
import { join } from 'node:path';
import { PNG } from 'pngjs';
import { isPortalSpot, type Catalog, type OfficeBundle } from '@pixeloffice/core';
import type { RenderedMap } from '@pixeloffice/protocol';

type Rgba = [number, number, number, number];
type Frame = { sheet: string; x: number; y: number; w: number; h: number };
export type SheetSource = { get(name: string): Promise<PNG> };
export type PreviewImages = { plain: Buffer; grid: Buffer };
export type Bounds = { minX: number; minY: number; maxX: number; maxY: number };

// Поля картинки grid под подписи осей: рамка, слева — номера строк, сверху — номера столбцов.
export const PREVIEW_MARGIN = { frame: 6, axisX: 30, axisY: 26 };
// Цвета слоёв grid (спека хостинга 7.2): рамки зон по виду и точки мест по виду места. Объясняет их инструкция
// (previewLegend), поэтому цвета живут здесь, одним местом.
export const PREVIEW_COLORS = {
  zone: { pod: [40, 110, 230, 255] as Rgba, meeting: [235, 140, 20, 255] as Rgba, common: [30, 170, 80, 255] as Rgba },
  spot: { work: [20, 70, 200, 255] as Rgba, meeting: [215, 100, 0, 255] as Rgba, common: [10, 130, 50, 255] as Rgba, portal: [200, 40, 200, 255] as Rgba },
};
const GRID_LIGHT: Rgba = [120, 40, 40, 90];
const GRID_DARK: Rgba = [120, 40, 40, 200];
const AXIS_TEXT: Rgba = [170, 30, 30, 255];
const AXIS_PLATE: Rgba = [255, 255, 255, 200];

// Листы арта из assetsDir: читаются один раз и живут в памяти процесса. Чтение потоком: PNG.sync.read (pngjs 7)
// падает на валидных больших листах («unrecognised content at end of stream»).
export class SheetCache implements SheetSource {
  private readonly cache = new Map<string, Promise<PNG>>();
  private readonly assetsDir: string;
  private readonly catalog: Catalog;

  constructor(assetsDir: string, catalog: Catalog) {
    this.assetsDir = assetsDir;
    this.catalog = catalog;
  }

  get(name: string): Promise<PNG> {
    const hit = this.cache.get(name);
    if (hit) return hit;
    const rel = name.startsWith('/sprites/') ? name.slice('/sprites/'.length) : this.catalog.sheets[name];
    const p = new Promise<PNG>((res, rej) => {
      if (!rel) return rej(new Error(`лист «${name}» не найден в каталоге`));
      createReadStream(join(this.assetsDir, rel))
        .on('error', rej)
        .pipe(new PNG())
        .on('parsed', function (this: PNG) {
          res(this);
        })
        .on('error', rej);
    });
    p.catch(() => this.cache.delete(name)); // неудачное чтение не кешируется
    this.cache.set(name, p);
    return p;
  }
}

// Границы мира в пикселях: здание, земля участка и спрайты (верх стен выступает над картой).
export function previewBounds(r: RenderedMap): Bounds {
  const TS = r.tileSize;
  let minX = 0;
  let minY = 0;
  let maxX = r.width * TS;
  let maxY = r.height * TS;
  for (const g of r.site ? r.site.ground : []) {
    minX = Math.min(minX, g.x * TS);
    minY = Math.min(minY, g.y * TS);
    maxX = Math.max(maxX, (g.x + 1) * TS);
    maxY = Math.max(maxY, (g.y + 1) * TS);
  }
  for (const s of r.sprites) {
    minX = Math.min(minX, s.px);
    minY = Math.min(minY, s.py);
    maxX = Math.max(maxX, s.px + s.frame.w);
    maxY = Math.max(maxY, s.py + s.frame.h);
  }
  return { minX, minY, maxX, maxY };
}

// Холст: мировые пиксели → экранные со сдвигом (ox, oy); наложение source-over.
class Canvas {
  readonly png: PNG;
  private readonly ox: number;
  private readonly oy: number;

  constructor(w: number, h: number, ox: number, oy: number) {
    this.png = new PNG({ width: w, height: h });
    this.ox = ox;
    this.oy = oy;
  }

  sx(wx: number): number {
    return wx + this.ox;
  }

  sy(wy: number): number {
    return wy + this.oy;
  }

  // Пиксель в экранных координатах.
  put(x: number, y: number, [r, g, b, a]: Rgba): void {
    const { width, height, data } = this.png;
    if (x < 0 || y < 0 || x >= width || y >= height || a === 0) return;
    const i = (y * width + x) * 4;
    const d = a / 255;
    data[i] = Math.round(data[i]! * (1 - d) + r * d);
    data[i + 1] = Math.round(data[i + 1]! * (1 - d) + g * d);
    data[i + 2] = Math.round(data[i + 2]! * (1 - d) + b * d);
    data[i + 3] = Math.max(data[i + 3]!, a);
  }

  // Кадр листа в мировой точке (wx, wy); пиксели за краем листа пропускаются (пустые листы в тестах).
  blit(src: PNG, f: Frame, wx: number, wy: number): void {
    for (let y = 0; y < f.h; y++)
      for (let x = 0; x < f.w; x++) {
        const fx = f.x + x;
        const fy = f.y + y;
        if (fx >= src.width || fy >= src.height) continue;
        const i = (fy * src.width + fx) * 4;
        if (src.data[i + 3]) this.put(this.sx(wx) + x, this.sy(wy) + y, [src.data[i]!, src.data[i + 1]!, src.data[i + 2]!, src.data[i + 3]!]);
      }
  }
}

// Мини-шрифт 3×5 масштабом 2 на белой плашке: цифры и минус (подписи осей).
const FONT: Record<string, string[]> = {
  '0': ['111', '101', '101', '101', '111'], '1': ['010', '110', '010', '010', '111'], '2': ['111', '001', '111', '100', '111'],
  '3': ['111', '001', '111', '001', '111'], '4': ['101', '101', '111', '001', '001'], '5': ['111', '100', '111', '001', '111'],
  '6': ['111', '100', '111', '101', '111'], '7': ['111', '001', '010', '010', '010'], '8': ['111', '101', '111', '101', '111'],
  '9': ['111', '101', '111', '001', '111'], '-': ['000', '000', '111', '000', '000'],
};
function text(c: Canvas, str: string, x: number, y: number): void {
  for (let yy = -2; yy < 12; yy++) for (let xx = -2; xx < str.length * 8 + 2; xx++) c.put(x + xx, y + yy, AXIS_PLATE);
  [...str].forEach((ch, k) => {
    const g = FONT[ch];
    if (!g) return;
    for (let yy = 0; yy < 5; yy++)
      for (let xx = 0; xx < 3; xx++)
        if (g[yy]![xx] === '1') for (const [dx, dy] of [[0, 0], [1, 0], [0, 1], [1, 1]]) c.put(x + k * 8 + xx * 2 + dx!, y + yy * 2 + dy!, AXIS_TEXT);
  });
}

// Арт карты: земля участка → пол → первые кадры раздвижных дверей → спрайты по sortY. Крыш нет: иначе не видно комнат.
function paint(c: Canvas, r: RenderedMap, sheets: Map<string, PNG>): void {
  const TS = r.tileSize;
  const blit = (f: Frame, wx: number, wy: number) => c.blit(sheets.get(f.sheet)!, f, wx, wy);
  for (const g of r.site ? r.site.ground : []) for (const f of g.frames) blit(f, g.x * TS, g.y * TS);
  for (const f of r.floor) blit(f.frame, f.x * TS, f.y * TS);
  for (const d of r.doors) blit(d.frames[0]!, d.px, d.py);
  for (const s of [...r.sprites].sort((a, b) => a.sortY - b.sortY)) blit(s.frame, s.px, s.py);
}

// Слои grid (спека хостинга 7.2): сетка, рамки зон, точки мест, подписи осей.
function overlay(c: Canvas, b: OfficeBundle, bb: Bounds): void {
  const TS = b.rendered.tileSize;
  const { width: W, height: H } = c.png;
  for (let cx = Math.floor(bb.minX / TS); cx * TS <= bb.maxX; cx++) for (let y = 0; y < H; y++) c.put(c.sx(cx * TS), y, cx % 5 === 0 ? GRID_DARK : GRID_LIGHT);
  for (let cy = Math.floor(bb.minY / TS); cy * TS <= bb.maxY; cy++) for (let x = 0; x < W; x++) c.put(x, c.sy(cy * TS), cy % 5 === 0 ? GRID_DARK : GRID_LIGHT);
  // Рамка зоны — 1 px, на 1 px внутрь от границы клеток: линия сетки её не перекрывает.
  for (const z of b.map.zones) {
    const col = PREVIEW_COLORS.zone[z.kind];
    const x0 = z.rect[0] * TS + 1;
    const y0 = z.rect[1] * TS + 1;
    const x1 = (z.rect[0] + z.rect[2]) * TS - 2;
    const y1 = (z.rect[1] + z.rect[3]) * TS - 2;
    for (let x = x0; x <= x1; x++) {
      c.put(c.sx(x), c.sy(y0), col);
      c.put(c.sx(x), c.sy(y1), col);
    }
    for (let y = y0; y <= y1; y++) {
      c.put(c.sx(x0), c.sy(y), col);
      c.put(c.sx(x1), c.sy(y), col);
    }
  }
  // Точка места 4×4 в центре клетки: портал; иначе по виду зоны места; место без зоны — общее.
  for (const s of b.map.spots) {
    const kind = b.map.zones.find((z) => z.id === s.zoneId)?.kind;
    const col = isPortalSpot(s) ? PREVIEW_COLORS.spot.portal : kind === 'pod' ? PREVIEW_COLORS.spot.work : kind === 'meeting' ? PREVIEW_COLORS.spot.meeting : PREVIEW_COLORS.spot.common;
    const cx = s.x * TS + TS / 2;
    const cy = s.y * TS + TS / 2;
    for (let dy = -2; dy < 2; dy++) for (let dx = -2; dx < 2; dx++) c.put(c.sx(cx + dx), c.sy(cy + dy), col);
  }
  for (let cx = Math.floor(bb.minX / TS); cx <= Math.ceil(bb.maxX / TS); cx++) text(c, String(cx), c.sx(cx * TS) + 1, 6);
  for (let cy = Math.floor(bb.minY / TS); cy <= Math.ceil(bb.maxY / TS); cy++) text(c, String(cy), 2, c.sy(cy * TS) + 2);
}

// Картинки предпросмотра (спека хостинга 7.2): 1:1, клетка — tileSize каталога, без персонажей и машин, первый кадр
// раздвижных дверей, без крыш. Текст и логотип вывески — шрифт вьюера, не рисуются; плашка — спрайт, рисуется.
export async function renderPreview(b: OfficeBundle, sheets: SheetSource): Promise<PreviewImages> {
  const r = b.rendered;
  const names = new Set<string>();
  for (const f of r.floor) names.add(f.frame.sheet);
  for (const s of r.sprites) names.add(s.frame.sheet);
  for (const g of r.site ? r.site.ground : []) for (const f of g.frames) names.add(f.sheet);
  for (const d of r.doors) names.add(d.frames[0]!.sheet);
  const list = [...names];
  const loaded = await Promise.all(list.map((n) => sheets.get(n)));
  const map = new Map(list.map((n, i) => [n, loaded[i]!]));
  const bb = previewBounds(r);
  const W = bb.maxX - bb.minX;
  const H = bb.maxY - bb.minY;
  const M = PREVIEW_MARGIN;
  const plain = new Canvas(W, H, -bb.minX, -bb.minY);
  paint(plain, r, map);
  const grid = new Canvas(W + 2 * M.frame + M.axisX, H + 2 * M.frame + M.axisY, -bb.minX + M.frame + M.axisX, -bb.minY + M.frame + M.axisY);
  paint(grid, r, map);
  overlay(grid, b, bb);
  return { plain: PNG.sync.write(plain.png), grid: PNG.sync.write(grid.png) };
}

const hex = ([r, g, b]: Rgba) => '#' + [r, g, b].map((v) => v.toString(16).padStart(2, '0')).join('');

// Легенда цветов для инструкции (спека хостинга 8.1): таблица из PREVIEW_COLORS — текст и картинка не разойдутся.
export function previewLegend(): string {
  const z = PREVIEW_COLORS.zone;
  const s = PREVIEW_COLORS.spot;
  const rows: [string, Rgba, string][] = [
    ['рамка зоны pod', z.pod, 'рабочие кабинки людей'],
    ['рамка зоны meeting', z.meeting, 'переговорка'],
    ['рамка зоны common', z.common, 'общая зона: лаунж, коворкинг'],
    ['точка в клетке', s.work, 'рабочее место в кабинке'],
    ['точка в клетке', s.meeting, 'место на встрече'],
    ['точка в клетке', s.common, 'место в общей зоне'],
    ['точка в клетке', s.portal, 'портал: остановка, капсула дока агентов, спальное место в парке'],
  ];
  return [
    '| Что | Цвет | Значит |',
    '|---|---|---|',
    ...rows.map(([what, col, meaning]) => `| ${what} | \`${hex(col)}\` | ${meaning} |`),
    '',
    'Сетка — клетки по 16 px, каждая пятая линия темнее. Номера столбцов — сверху, номера строк — слева.',
  ].join('\n');
}
