#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
中文字体安装工具

此脚本用于下载和安装中文字体，以支持PDF生成功能。
"""

import os
import sys
import logging
import shutil
import tempfile
import platform

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

def download_wqy_font():
    """
    下载文泉驿微米黑字体
    
    Returns:
        str: 下载的字体文件路径，如果失败则返回None
    """
    try:
        import requests
        
        # 创建临时目录
        temp_dir = tempfile.mkdtemp()
        font_file = os.path.join(temp_dir, "wqy-microhei.ttc")
        
        # 文泉驿微米黑字体的下载链接
        url = "https://mirrors.tuna.tsinghua.edu.cn/osdn/wqy/wqy-microhei-0.2.0-beta.tar.gz"
        
        logger.info(f"开始下载文泉驿微米黑字体: {url}")
        response = requests.get(url, stream=True)
        response.raise_for_status()
        
        # 下载压缩包
        tar_file = os.path.join(temp_dir, "wqy-microhei.tar.gz")
        with open(tar_file, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)
        
        # 解压字体文件
        import tarfile
        with tarfile.open(tar_file) as tar:
            # 提取字体文件
            for member in tar.getmembers():
                if member.name.endswith(('.ttc', '.ttf')):
                    member.name = os.path.basename(member.name)
                    tar.extract(member, temp_dir)
                    extracted_file = os.path.join(temp_dir, member.name)
                    if os.path.exists(extracted_file):
                        return extracted_file
        
        logger.error("在压缩包中未找到字体文件")
        return None
    
    except Exception as e:
        logger.error(f"下载字体失败: {str(e)}")
        return None
    
def find_system_fonts():
    """
    在系统中查找可用的中文字体
    
    Returns:
        str: 找到的字体文件路径，如果找不到则返回None
    """
    # 常见的中文字体位置
    font_locations = []
    
    system = platform.system()
    if system == "Windows":
        font_locations = [
            "C:/Windows/Fonts/simhei.ttf",
            "C:/Windows/Fonts/simsun.ttc",
            "C:/Windows/Fonts/msyh.ttf",
            "C:/Windows/Fonts/simfang.ttf",
        ]
    elif system == "Darwin":  # macOS
        font_locations = [
            "/System/Library/Fonts/PingFang.ttc",
            "/Library/Fonts/Microsoft/SimHei.ttf",
            "/Library/Fonts/Microsoft/SimSun.ttf",
        ]
    else:  # Linux
        font_locations = [
            "/usr/share/fonts/truetype/wqy/wqy-microhei.ttc",
            "/usr/share/fonts/wqy-microhei/wqy-microhei.ttc",
            "/usr/share/fonts/wenquanyi/wqy-microhei/wqy-microhei.ttc",
            "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
            "/usr/share/fonts/truetype/droid/DroidSansFallback.ttf",
        ]
    
    # 查找第一个存在的字体文件
    for font_path in font_locations:
        if os.path.exists(font_path):
            logger.info(f"在系统中找到中文字体: {font_path}")
            return font_path
    
    logger.warning("在系统中未找到任何中文字体")
    return None

def install_font(target_dir=None):
    """
    安装中文字体
    
    Args:
        target_dir: 目标目录，如果不提供则使用默认目录
        
    Returns:
        str: 安装后的字体文件路径，如果失败则返回None
    """
    # 如果没有指定目标目录，使用默认位置
    if target_dir is None:
        # 获取当前脚本所在目录
        current_dir = os.path.dirname(os.path.abspath(__file__))
        target_dir = os.path.join(current_dir, "fonts")
    
    # 确保目标目录存在
    os.makedirs(target_dir, exist_ok=True)
    
    # 目标字体文件路径
    target_font = os.path.join(target_dir, "simhei.ttf")
    
    # 如果目标字体已存在，直接返回
    if os.path.exists(target_font):
        logger.info(f"中文字体已存在: {target_font}")
        return target_font
    
    # 尝试从系统中复制字体
    system_font = find_system_fonts()
    if system_font:
        try:
            shutil.copy2(system_font, target_font)
            logger.info(f"已从系统复制字体: {system_font} -> {target_font}")
            return target_font
        except Exception as e:
            logger.error(f"复制系统字体失败: {str(e)}")
    
    # 如果系统中找不到字体，尝试下载
    logger.info("尝试下载中文字体...")
    downloaded_font = download_wqy_font()
    if downloaded_font:
        try:
            shutil.copy2(downloaded_font, target_font)
            logger.info(f"已安装下载的字体: {downloaded_font} -> {target_font}")
            return target_font
        except Exception as e:
            logger.error(f"复制下载的字体失败: {str(e)}")
    
    logger.error("安装中文字体失败")
    return None

def main():
    """
    主函数
    """
    print("中文字体安装工具")
    print("----------------")
    
    target_dir = None
    if len(sys.argv) > 1:
        target_dir = sys.argv[1]
        print(f"使用指定的目标目录: {target_dir}")
    
    result = install_font(target_dir)
    
    if result:
        print(f"\n✓ 成功安装中文字体: {result}")
        print("\n现在可以正常生成PDF报告了。")
    else:
        print("\n✗ 安装中文字体失败")
        print("\n请手动将中文字体(.ttf或.ttc文件)复制到以下目录:")
        if target_dir:
            print(f"  {target_dir}")
        else:
            print(f"  {os.path.join(os.path.dirname(os.path.abspath(__file__)), 'fonts')}")
        print("\n并将其重命名为'simhei.ttf'")

if __name__ == "__main__":
    main() 