import { existsSync } from "node:fs";
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
/**
 * Resolve a drawtext-usable font for burned subtitles. Order:
 *   1. DP_RENDER_FONT_PATH (explicit override)
 *   2. A system font from the candidate list (incl. macOS CJK fonts — the
 *      production hosts are Macs, so PingFang/STHeiti give reliable Chinese).
 *   3. Download DP_RENDER_FONT_URL into <workspace>/fonts (cached) — for Linux
 *      hosts without a bundled CJK font.
 *   4. null → caller skips subtitle burning (render still succeeds).
 */
const CANDIDATES = [
    process.env.DP_RENDER_FONT_PATH,
    // macOS (CJK-capable)
    "/System/Library/Fonts/PingFang.ttc",
    "/System/Library/Fonts/STHeiti Medium.ttc",
    "/System/Library/Fonts/Hiragino Sans GB.ttc",
    "/System/Library/Fonts/Supplemental/Arial Unicode.ttf",
    "/System/Library/Fonts/Supplemental/Arial.ttf",
    "/Library/Fonts/Arial Unicode.ttf",
    // Linux
    "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
    "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
    "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
    "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
].filter((p) => Boolean(p));
let cached;
export async function ensureFont(workspace) {
    if (cached !== undefined)
        return cached;
    for (const c of CANDIDATES) {
        if (existsSync(c)) {
            cached = c;
            return c;
        }
    }
    const url = process.env.DP_RENDER_FONT_URL;
    if (url) {
        try {
            const dir = path.join(workspace, "fonts");
            await mkdir(dir, { recursive: true });
            const dest = path.join(dir, url.toLowerCase().endsWith(".otf") ? "subtitle.otf" : "subtitle.ttf");
            if (!existsSync(dest)) {
                const res = await fetch(url);
                if (res.ok)
                    await writeFile(dest, new Uint8Array(await res.arrayBuffer()));
            }
            if (existsSync(dest)) {
                cached = dest;
                return dest;
            }
        }
        catch {
            /* fall through */
        }
    }
    cached = null;
    return null;
}
//# sourceMappingURL=font.js.map