import { mkdirSync, writeFileSync, readFileSync, existsSync } from "node:fs"
import path from "node:path"
import { fileURLToPath } from "node:url"
import sharp from "sharp"

const __dirname = path.dirname(fileURLToPath(import.meta.url))

async function main() {
  const args = process.argv.slice(2)
  if (args.length < 2) {
    process.stderr.write("usage: node render.mjs <svg-file> <out-path>\n")
    process.exit(2)
  }
  const svgFile = args[0]
  const outPath = args[1]

  const svg = readFileSync(svgFile, "utf-8")

  const outDir = path.dirname(outPath)
  if (outDir && !existsSync(outDir)) {
    mkdirSync(outDir, { recursive: true })
  }

  const fontDir = path.join(__dirname, "fonts")
  const fontFiles = []
  const sansTtf = path.join(fontDir, "Geist-Regular.ttf")
  const sansBoldTtf = path.join(fontDir, "Geist-Bold.ttf")
  if (existsSync(sansTtf)) fontFiles.push(sansTtf)
  if (existsSync(sansBoldTtf)) fontFiles.push(sansBoldTtf)

  const pngOpts = { compressionLevel: 9 }
  if (fontFiles.length > 0) {
    pngOpts.fontFiles = fontFiles
  }

  await sharp(Buffer.from(svg), { density: 72 })
    .png(pngOpts)
    .toFile(outPath)
}

main().catch((err) => {
  process.stderr.write(`render failed: ${err instanceof Error ? err.message : String(err)}\n`)
  process.exit(1)
})