/**
 * Download curated watermark fonts into assets/fonts for FFmpeg drawtext.
 * Run: node scripts/fetch-watermark-fonts.mjs
 */
import fs from "fs/promises";
import path from "path";
import { fileURLToPath } from "url";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const outDir = path.join(__dirname, "..", "assets", "fonts");

/** Direct TTF URLs from Google Fonts GitHub (OFL / Apache 2.0). */
const FONTS = [
  {
    file: "Arimo-Regular.ttf",
    // Static TTF from googlefonts/arimo (not the broken google/fonts apache/static path)
    url: "https://cdn.jsdelivr.net/gh/googlefonts/arimo@main/fonts/ttf/Arimo-Regular.ttf",
  },
  {
    file: "Arimo-Bold.ttf",
    url: "https://cdn.jsdelivr.net/gh/googlefonts/arimo@main/fonts/ttf/Arimo-Bold.ttf",
  },
  {
    file: "Inter-Regular.ttf",
    url: "https://github.com/google/fonts/raw/main/ofl/inter/Inter%5Bopsz%2Cwght%5D.ttf",
  },
  {
    file: "Montserrat-Regular.ttf",
    url: "https://github.com/google/fonts/raw/main/ofl/montserrat/Montserrat%5Bwght%5D.ttf",
  },
  {
    file: "Roboto-Regular.ttf",
    url: "https://github.com/google/fonts/raw/main/ofl/roboto/Roboto%5Bwdth%2Cwght%5D.ttf",
  },
  {
    file: "Oswald-Regular.ttf",
    url: "https://github.com/google/fonts/raw/main/ofl/oswald/Oswald%5Bwght%5D.ttf",
  },
  {
    file: "PlayfairDisplay-Regular.ttf",
    url: "https://github.com/google/fonts/raw/main/ofl/playfairdisplay/PlayfairDisplay%5Bwght%5D.ttf",
  },
];

await fs.mkdir(outDir, { recursive: true });

function looksLikeFont(buf) {
  if (buf.length < 4) return false;
  const asStr = buf.subarray(0, 4).toString("ascii");
  if (asStr === "OTTO" || asStr === "true" || asStr === "typ1") return true;
  return buf[0] === 0x00 && buf[1] === 0x01 && buf[2] === 0x00 && buf[3] === 0x00;
}

for (const font of FONTS) {
  const dest = path.join(outDir, font.file);
  try {
    const existing = await fs.readFile(dest);
    if (looksLikeFont(existing)) {
      console.log("skip (exists)", font.file);
      continue;
    }
    console.warn("corrupt font, re-fetching", font.file);
  } catch {
    /* download */
  }
  console.log("fetch", font.file);
  const res = await fetch(font.url, {
    headers: { "User-Agent": "songs2vid-font-fetch/1.0" },
    redirect: "follow",
  });
  if (!res.ok) {
    console.error("FAILED", font.file, res.status);
    continue;
  }
  const buf = Buffer.from(await res.arrayBuffer());
  if (!looksLikeFont(buf)) {
    console.error("FAILED invalid font bytes", font.file, buf.subarray(0, 8).toString("hex"));
    continue;
  }
  await fs.writeFile(dest, buf);
  console.log("wrote", font.file, buf.length, "bytes");
}

await fs.writeFile(
  path.join(outDir, "README.md"),
  `# Watermark fonts

Curated TTF assets for FFmpeg \`drawtext\` (OFL via Google Fonts).
Refresh with \`node scripts/fetch-watermark-fonts.mjs\`.
`,
  "utf8",
);

console.log("done →", outDir);
