import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import sharp from 'sharp'
import toIco from 'to-ico'

const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const siteDir = path.join(root, 'assets', 'site')
const sourcePng = path.join(siteDir, 'apple-touch-icon.png')

if (!fs.existsSync(sourcePng)) {
  console.warn('[generate-icons] 跳过：未找到 apple-touch-icon.png')
  process.exit(0)
}

async function resizePng(size) {
  return sharp(sourcePng).resize(size, size).png().toBuffer()
}

const icoSizes = [16, 32, 48, 64, 128, 256]
const icoBuffers = await Promise.all(icoSizes.map((size) => resizePng(size)))
const icoBuffer = await toIco(icoBuffers)

fs.writeFileSync(path.join(siteDir, 'favicon.ico'), icoBuffer)
fs.writeFileSync(path.join(siteDir, 'icon-192.png'), await resizePng(192))
fs.writeFileSync(path.join(siteDir, 'icon-512.png'), await resizePng(512))
fs.writeFileSync(path.join(siteDir, 'favicon.png'), await resizePng(512))

console.log('[generate-icons] 已生成 favicon.ico、icon-192.png、icon-512.png')
