# conf.py - Sphinx 知识库终极配置

import os,sys
import shutil
from pathlib import Path

# ================= 基础配置 =================
project = 'ManLin_KnowledgeBase'
copyright = '2024, YuYang Shen'
author = 'YuYang Shen'
release = '1.0'
language = 'zh_CN'

# 设置源文件编码为UTF-8（解决中文乱码问题）
source_encoding = 'utf-8'

# ================= 扩展配置 =================
extensions = [
    'myst_parser',           # Markdown支持
    'sphinx_copybutton',     # 代码复制按钮
    'sphinx_design',         # UI组件
    'sphinxcontrib.images',  # 图片管理
    'sphinxcontrib.video',   # 视频嵌入
    'sphinxcontrib.htmlhelp',# CHM 生成
    'sphinxcontrib.wavedrom' # 时序图
]

# ================= MyST配置 =================
myst_enable_extensions = [
    "colon_fence",
    "deflist",
    "tasklist",
    "html_image"
]

myst_heading_anchors=5

# ================= 路径配置 =================
exclude_patterns = [
    '_templates/*',   # 忽略模板目录
    '**/*.template',  # 忽略模板文件
    'Thumbs.db'       # 忽略系统文件
]
templates_path = ['_templates']
html_static_path = ['_static']

# ================= 构建控制 =================
is_chm_build = 'htmlhelp' in sys.argv

wavedrom_html_jsinline = False  # 离线渲染

# ================= 主题配置 =================

html_theme = 'sphinx_rtd_theme'
html_theme_options = {
    'collapse_navigation': False,
    'includehidden': True
}


# ================= 高级功能 =================
html_js_files = [
    'custom.js'
]

# ================== Mermaid 配置 ==================
def find_system_chrome():
    """自动检测系统 Chrome/Chromium 可执行路径"""
    # 按优先级检查的浏览器名称
    chrome_names = [
        'google-chrome',        # 官方 Chrome
        'google-chrome-stable',  # Stable 版本
        'chromium',             # Chromium
        'chromium-browser',     # Debian 系命名
        'chrome',               # 备用名称
        'microsoft-edge'        # Edge 兼容
    ]
    
    # 1. 尝试通过 which 查找
    for name in chrome_names:
        chrome_path = shutil.which(name)
        if chrome_path:
            return chrome_path
    
    # 2. 检查常见安装路径
    common_paths = [
        '/usr/bin/',
        '/usr/local/bin/',
        '/opt/google/chrome/',
        '/snap/bin/',
        '/Applications/Google Chrome.app/Contents/MacOS/'  # macOS
    ]
    
    for path in common_paths:
        for name in chrome_names:
            chrome_path = Path(path) / name
            if chrome_path.exists():
                return str(chrome_path)
    
    raise RuntimeError("未找到 Chrome/Chromium 可执行文件")

try:
    # 获取系统 Chrome 路径
    chrome_path = find_system_chrome()
    
    if chrome_path:
        print(f"✅ 找到 Chrome 浏览器: {chrome_path}")
        # 设置环境变量，让 mermaid-cli 使用系统 Chrome
        os.environ['PUPPETEER_EXECUTABLE_PATH'] = chrome_path
        os.environ['PUPPETEER_SKIP_CHROMIUM_DOWNLOAD'] = 'true'
        
        # 添加 mermaid 扩展
        extensions.append('sphinxcontrib.mermaid')


        mermaid_output_format = 'png'
            
        print(f"✅ Mermaid 配置成功，输出格式: {mermaid_output_format}")
        
    
except Exception as e:
    print(f"⚠️ Mermaid 初始化失败: {e}")
    print("⚠️ 图表将显示为代码块，请安装 Chrome 和 mermaid-cli")

# ================= CHM特化配置 =================
if is_chm_build:
    html_compact_lists = True
    html_use_smartypants = False
    html_use_index = False
    html_scaled_image_link = False
    html_add_permalinks = False  # 禁用锚点（CHM 不支持）
    html_show_sourcelink = False  # 禁用源码链接
    htmlhelp_basename = 'ManLinKB'
    html_css_files = []
    html_js_files = []
    
# 公共配置
html_last_updated_fmt = '%Y-%m-%d'  # 最后更新时间