using System;
using System.IO;
using PdfSharpCore.Fonts;

namespace CounterDrone.Core.Reporting
{
    /// <summary>CJK 字体解析器 — 从文件路径加载 TrueType 字体供 PdfSharpCore 使用</summary>
    public sealed class CjkFontResolver : IFontResolver
    {
        private readonly byte[] _fontData;
        private readonly string _familyName;

        /// <summary>注册 CJK 字体解析器到全局设置（进程内只能注册一次）</summary>
        /// <param name="fontPath">CJK TrueType/OpenType 字体文件路径</param>
        /// <param name="familyName">字体族名（用于 XFont 构造）</param>
        public static void Register(string fontPath, string familyName)
        {
            if (string.IsNullOrEmpty(fontPath))
                throw new ArgumentException("字体路径不能为空", nameof(fontPath));
            if (!File.Exists(fontPath))
                throw new FileNotFoundException($"字体文件不存在: {fontPath}", fontPath);

            if (GlobalFontSettings.FontResolver == null)
                GlobalFontSettings.FontResolver = new CjkFontResolver(fontPath, familyName);
        }

        private CjkFontResolver(string fontPath, string familyName)
        {
            _fontData = File.ReadAllBytes(fontPath);
            _familyName = familyName;
        }

        public FontResolverInfo ResolveTypeface(string familyName, bool isBold, bool isItalic)
            => new FontResolverInfo(_familyName);

        public byte[] GetFont(string faceName) => _fontData;

        public string DefaultFontName => _familyName;
    }
}
