using SkiaSharp;

namespace Jiaowu.Api.Infrastructure.Pdf;

/// <summary>
/// Resolves the CJK typeface used by every server-generated PDF.
/// A configured font takes precedence so production exports do not silently
/// fall back to a font without Chinese glyphs.
/// </summary>
public static class PdfTypefaceResolver
{
    public static SKTypeface ResolveChineseTypeface(string? configuredFontPath)
    {
        if (!string.IsNullOrWhiteSpace(configuredFontPath))
            return Load(configuredFontPath) ?? throw new InvalidOperationException(
                $"无法加载已配置的 PDF 中文字体：{configuredFontPath}。");

        var candidates = new[]
        {
            Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "simhei.ttf"),
            Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "msyh.ttc"),
            "/usr/share/fonts/noto/NotoSansCJK-Regular.ttc",
            "/usr/share/fonts/noto-cjk/NotoSansCJK-Regular.ttc"
        };
        foreach (var candidate in candidates)
        {
            var typeface = Load(candidate);
            if (typeface is not null) return typeface;
        }

        throw new InvalidOperationException(
            "未找到可用于 PDF 导出的中文字体。请配置 OfficialDocuments:FontPath。");
    }

    private static SKTypeface? Load(string path) =>
        File.Exists(path) ? SKTypeface.FromFile(path) : null;
}
