import { readFileSync } from 'node:fs';
import { createRequire } from 'node:module';
import { dirname, join } from 'node:path';
import { PNG } from 'pngjs';

// Логотип вывески из эмодзи (спека хостинга 5.7): картинка Noto 64×64 из пакета emoji-datasource-google
// (Apache 2.0) уменьшается до плотного логотипа size×size. Ни шрифтов, ни программ у ИИ не нужно.
export const EMOJI_LOGO_SIZES = [20, 30] as const;
export type EmojiLogoSize = (typeof EMOJI_LOGO_SIZES)[number];
// Полупрозрачная кайма после уменьшения: ниже порога — прозрачно, выше — непрозрачно, как у пиксель-арта вокруг.
const ALPHA_CUT = 96;

type Entry = { unified: string; non_qualified?: string | null; image: string; has_img_google?: boolean; skin_variations?: Record<string, Entry> };

// Ключ — коды символа без FE0F (селектор варианта): «😈», «😈️» и запись из таблицы сходятся в один.
const key = (codes: string[]) => codes.map((c) => c.toLowerCase()).filter((c) => c !== 'fe0f').join('-');
const keyOf = (emoji: string) => key([...emoji].map((ch) => ch.codePointAt(0)!.toString(16)));

export class EmojiImages {
  private readonly files = new Map<string, string>();
  private readonly dir: string;

  constructor() {
    const json = createRequire(import.meta.url).resolve('emoji-datasource-google/emoji.json');
    this.dir = join(dirname(json), 'img', 'google', '64');
    const add = (e: Entry) => {
      if (e.has_img_google === false) return;
      this.files.set(key(e.unified.split('-')), e.image);
      if (e.non_qualified) this.files.set(key(e.non_qualified.split('-')), e.image);
    };
    for (const e of JSON.parse(readFileSync(json, 'utf8')) as Entry[]) {
      add(e);
      for (const v of Object.values(e.skin_variations ?? {})) add(v);
    }
  }

  // PNG 64×64 эмодзи или null, если такого в наборе нет.
  read(emoji: string): PNG | null {
    const file = this.files.get(keyOf(emoji));
    return file ? PNG.sync.read(readFileSync(join(this.dir, file))) : null;
  }
}

// Уменьшение усреднением по площади с весом альфы: цвет полупрозрачной кромки не темнеет к чёрному.
export function downscale(src: PNG, n: number): PNG {
  const out = new PNG({ width: n, height: n });
  const sx = src.width / n;
  const sy = src.height / n;
  for (let y = 0; y < n; y++)
    for (let x = 0; x < n; x++) {
      let r = 0, g = 0, b = 0, a = 0, w = 0;
      for (let py = Math.floor(y * sy); py < Math.ceil((y + 1) * sy); py++)
        for (let px = Math.floor(x * sx); px < Math.ceil((x + 1) * sx); px++) {
          const wt = (Math.min(px + 1, (x + 1) * sx) - Math.max(px, x * sx)) * (Math.min(py + 1, (y + 1) * sy) - Math.max(py, y * sy));
          const i = (py * src.width + px) * 4;
          const al = (src.data[i + 3]! / 255) * wt;
          r += src.data[i]! * al;
          g += src.data[i + 1]! * al;
          b += src.data[i + 2]! * al;
          a += al;
          w += wt;
        }
      const i = (y * n + x) * 4;
      if ((a / w) * 255 < ALPHA_CUT) continue; // данные PNG уже нули — прозрачно
      out.data[i] = Math.round(r / a);
      out.data[i + 1] = Math.round(g / a);
      out.data[i + 2] = Math.round(b / a);
      out.data[i + 3] = 255;
    }
  return out;
}

export function emojiLogo(images: EmojiImages, emoji: string, size: EmojiLogoSize): Buffer | null {
  const src = images.read(emoji);
  return src ? PNG.sync.write(downscale(src, size)) : null;
}
