% Copyright 2026 Open-Guji (https://github.com/open-guji)
%
% Licensed under the Apache License, Version 2.0 (the "License");
% you may not use this file except in compliance with the License.
% You may obtain a copy of the License at
%
%     http://www.apache.org/licenses/LICENSE-2.0
%
% Unless required by applicable law or agreed to in writing, software
% distributed under the License is distributed on an "AS IS" BASIS,
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
% See the License for the specific language governing permissions and
% limitations under the License.

% luatex-cn-font-autodetect.sty
% 中文字体自动探测模块 - Automatic Chinese Font Detection for LuaLaTeX
%
% ============================================================================
% 功能说明 (Description)
% ============================================================================
% 本模块根据操作系统自动选择合适的中文字体：
%   - Windows: SimSun (宋体), SimHei (黑体), KaiTi (楷体), FangSong (仿宋)
%   - macOS:   Songti SC, PingFang SC, Kaiti SC, STFangsong
%   - Linux:   FandolSong, FandolHei, FandolKai, FandolFang (开源方正字体)
%              或 Noto Serif/Sans CJK SC (Google Noto 字体)
%
% ============================================================================
% 使用方法 (Usage)
% ============================================================================
%
% 方式一：配合 ltc-guji 文档类使用（推荐）
% ------------------------------------------
% ltc-guji 会自动加载本模块，无需手动设置字体：
%
%   \documentclass{ltc-guji}
%   \begin{document}
%   \begin{正文}
%   这里的文字会自动使用系统中文字体排版。
%   \end{正文}
%   \end{document}
%
% 如需手动指定字体，使用 font-name 参数覆盖自动探测：
%
%   \begin{正文}[font-name=Source Han Serif SC]
%   使用思源宋体排版。
%   \end{正文}
%
% 方式二：独立使用本模块
% ------------------------------------------
%   \documentclass{article}
%   \usepackage{fontspec}
%   \usepackage{luatex-cn-font-autodetect}
%
%   \begin{document}
%   \ApplyAutoFont  % 应用自动探测的字体
%   中文内容...
%   \end{document}
%
% ============================================================================
% 提供的命令 (Commands)
% ============================================================================
%
%   \ApplyAutoFont
%       应用自动探测的中文字体（调用 \setmainfont）
%
%   \GetAutoFontName
%       获取探测到的字体名称（可用于调试或显示）
%
%   \GetAutoFontFeatures
%       获取字体特性字符串（如 RawFeature={+vert,+vrt2}）
%
% ============================================================================
% 手动设置字体 (Manual Font Configuration)
% ============================================================================
% 如果自动探测的字体不符合需求，可以手动使用 fontspec：
%
%   \usepackage{fontspec}
%   \setmainfont{Your Font Name}[
%     RawFeature={+vert,+vrt2},  % 竖排字形
%     CharacterWidth=Full        % 全角字符
%   ]
%
% 常用中文字体：
%   - 思源宋体: Source Han Serif SC / Noto Serif CJK SC
%   - 思源黑体: Source Han Sans SC / Noto Sans CJK SC
%   - 方正字体: FZShuSong-Z01, FZKai-Z03, FZHei-B01, FZFangSong-Z02
%
% ============================================================================

\NeedsTeXFormat{LaTeX2e}
\ProvidesPackage{luatex-cn-font-autodetect}[2026/01/19 v0.1.1 Font Auto-Detection for Chinese]

\RequirePackage{ifluatex}
\RequirePackage{luatexbase}

% Ensure we're using LuaTeX
\ifluatex\else
  \PackageError{luatex-cn-font-autodetect}{%
    This package requires LuaLaTeX%
  }{%
    Please compile your document with lualatex.%
  }
\fi

% Load the Lua module
\directlua{
  texio.write_nl("term and log", "[Font Auto-Detect] Starting")
  fontdetect = nil
  local lua_file = kpse.find_file("luatex-cn-font-autodetect.lua", "lua")
  if lua_file then
    texio.write_nl("term and log", "[Font Auto-Detect] kpse found: " .. lua_file)
    fontdetect = dofile(lua_file)
  else
    texio.write_nl("term and log", "[Font Auto-Detect] kpse not found")
    local paths = {"../src/fonts/luatex-cn-font-autodetect.lua", "src/fonts/luatex-cn-font-autodetect.lua"}
    for _, path in ipairs(paths) do
      local f = io.open(path, "r")
      if f then
        f:close()
        texio.write_nl("term and log", "[Font Auto-Detect] Found: " .. path)
        fontdetect = dofile(path)
        break
      end
    end
  end
  if fontdetect then
    texio.write_nl("term and log", "[Font Auto-Detect] Module ready")
  else
    texio.write_nl("term and log", "[Font Auto-Detect] Creating stub")
    fontdetect = { get_font_setup = function() return nil end }
  end
}

% Command to apply auto-detected font
\newcommand{\ApplyAutoFont}{%
  \directlua{
    texio.write_nl("term and log", "[Font Auto-Detect] ApplyAutoFont command called")

    if not fontdetect then
      texio.write_nl("term and log", "[Font Auto-Detect] ERROR: fontdetect module not loaded")
      return
    end

    local font_setup = fontdetect.get_font_setup()
    if font_setup then
      texio.write_nl("term and log", "[Font Auto-Detect] Applying font: " .. font_setup.name)
      token.set_macro("fontauto@fontname", font_setup.name)
      token.set_macro("fontauto@features", font_setup.features)
    else
      texio.write_nl("term and log", "[Font Auto-Detect] No font configured, using LaTeX default")
      token.set_macro("fontauto@fontname", "")
    end
  }%
  \ifx\fontauto@fontname\empty\else
    \expandafter\setmainfont\expandafter{\fontauto@fontname}[\fontauto@features]%
  \fi
}

% Command to get auto-detected font name (for use in keys)
\newcommand{\GetAutoFontName}{%
  \directlua{
    local font_setup = fontdetect.get_font_setup()
    if font_setup then
      tex.print(font_setup.name)
    end
  }%
}

% Command to get auto-detected font features
\newcommand{\GetAutoFontFeatures}{%
  \directlua{
    local font_setup = fontdetect.get_font_setup()
    if font_setup then
      tex.print(font_setup.features)
    end
  }%
}

\endinput
