#!/usr/bin/env bash
# 字体下载脚本：思源宋体 + 思源黑体 + 霞鹜文楷
# 用法：bash .opencode/templates/fonts/download-fonts.sh
# 许可：全部 SIL OFL，可自由商用、嵌入 PDF 分发

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
FONTS_DIR="$SCRIPT_DIR"

echo "====================================="
echo "Deep Research 字体下载"
echo "目标目录：$FONTS_DIR"
echo "====================================="

# 检测下载工具
if command -v curl >/dev/null 2>&1; then
    DOWNLOADER="curl -fL --retry 3 --retry-delay 5 -o"
elif command -v wget >/dev/null 2>&1; then
    DOWNLOADER="wget -O"
else
    echo "❌ 需要 curl 或 wget，请先安装"
    exit 1
fi

# 字体清单：文件名 | 下载 URL
# 思源字体走 adobe-fonts GitHub Release 的 "Language Specific OTFs Simplified Chinese" 包
# 霞鹜文楷走 lxgw/LxgwWenKai Release
declare -a FONTS=(
    "SourceHanSerifSC-Regular.otf|https://github.com/adobe-fonts/source-han-serif/raw/release/SubsetOTF/CN/SourceHanSerifCN-Regular.otf"
    "SourceHanSerifSC-Bold.otf|https://github.com/adobe-fonts/source-han-serif/raw/release/SubsetOTF/CN/SourceHanSerifCN-Bold.otf"
    "SourceHanSansSC-Light.otf|https://github.com/adobe-fonts/source-han-sans/raw/release/SubsetOTF/CN/SourceHanSansCN-Light.otf"
    "SourceHanSansSC-Medium.otf|https://github.com/adobe-fonts/source-han-sans/raw/release/SubsetOTF/CN/SourceHanSansCN-Medium.otf"
    "SourceHanSansSC-Bold.otf|https://github.com/adobe-fonts/source-han-sans/raw/release/SubsetOTF/CN/SourceHanSansCN-Bold.otf"
    "SourceHanSansSC-Heavy.otf|https://github.com/adobe-fonts/source-han-sans/raw/release/SubsetOTF/CN/SourceHanSansCN-Heavy.otf"
    "LXGWWenKai-Regular.ttf|https://github.com/lxgw/LxgwWenKai/releases/download/v1.330/LXGWWenKai-Regular.ttf"
)

# 备用镜像（主源失败时用）
declare -a MIRRORS=(
    "SourceHanSerifSC-Regular.otf|https://raw.githubusercontent.com/adobe-fonts/source-han-serif/release/SubsetOTF/CN/SourceHanSerifCN-Regular.otf"
    "SourceHanSerifSC-Bold.otf|https://raw.githubusercontent.com/adobe-fonts/source-han-serif/release/SubsetOTF/CN/SourceHanSerifCN-Bold.otf"
    "SourceHanSansSC-Light.otf|https://raw.githubusercontent.com/adobe-fonts/source-han-sans/release/SubsetOTF/CN/SourceHanSansCN-Light.otf"
    "SourceHanSansSC-Medium.otf|https://raw.githubusercontent.com/adobe-fonts/source-han-sans/release/SubsetOTF/CN/SourceHanSansCN-Medium.otf"
    "SourceHanSansSC-Bold.otf|https://raw.githubusercontent.com/adobe-fonts/source-han-sans/release/SubsetOTF/CN/SourceHanSansCN-Bold.otf"
    "SourceHanSansSC-Heavy.otf|https://raw.githubusercontent.com/adobe-fonts/source-han-sans/release/SubsetOTF/CN/SourceHanSansCN-Heavy.otf"
    "LXGWWenKai-Regular.ttf|https://ghproxy.com/https://github.com/lxgw/LxgwWenKai/releases/download/v1.330/LXGWWenKai-Regular.ttf"
)

download_font() {
    local filename="$1"
    local url="$2"
    local target="$FONTS_DIR/$filename"

    if [[ -f "$target" ]]; then
        local size
        size=$(stat -f%z "$target" 2>/dev/null || stat -c%s "$target" 2>/dev/null || echo 0)
        if [[ $size -gt 100000 ]]; then
            echo "  ✓ 已存在（$size bytes），跳过：$filename"
            return 0
        else
            echo "  ⚠ 文件过小（$size bytes），重新下载：$filename"
            rm -f "$target"
        fi
    fi

    echo "  ↓ 下载 $filename ..."
    if $DOWNLOADER "$target" "$url" 2>/dev/null; then
        local size
        size=$(stat -f%z "$target" 2>/dev/null || stat -c%s "$target" 2>/dev/null || echo 0)
        if [[ $size -gt 100000 ]]; then
            echo "    ✓ 完成（$size bytes）"
            return 0
        else
            echo "    ⚠ 下载的文件过小，可能失败"
            rm -f "$target"
            return 1
        fi
    else
        echo "    ✗ 下载失败"
        rm -f "$target"
        return 1
    fi
}

get_mirror_url() {
    local filename="$1"
    for entry in "${MIRRORS[@]}"; do
        IFS='|' read -r fn url <<< "$entry"
        if [[ "$fn" == "$filename" ]]; then
            echo "$url"
            return 0
        fi
    done
    return 1
}

echo ""
echo "开始下载..."
echo ""

FAILED=()
for entry in "${FONTS[@]}"; do
    IFS='|' read -r filename url <<< "$entry"
    if ! download_font "$filename" "$url"; then
        # 主源失败，试镜像
        mirror_url=$(get_mirror_url "$filename" || true)
        if [[ -n "$mirror_url" ]]; then
            echo "  ↻ 尝试镜像..."
            if download_font "$filename" "$mirror_url"; then
                continue
            fi
        fi
        FAILED+=("$filename")
    fi
done

echo ""
echo "====================================="

if [[ ${#FAILED[@]} -eq 0 ]]; then
    echo "✅ 全部字体下载成功！"
    echo ""
    echo "字体文件清单："
    ls -lh "$FONTS_DIR" | grep -E '\.(otf|ttf)$' || true
    echo ""
    echo "许可证：全部 SIL OFL，可自由商用、嵌入 PDF 分发。"
    exit 0
else
    echo "❌ 以下字体下载失败："
    for f in "${FAILED[@]}"; do
        echo "   - $f"
    done
    echo ""
    echo "请手动下载，并放入 $FONTS_DIR/"
    echo ""
    echo "手动下载链接："
    echo "  思源宋体：https://github.com/adobe-fonts/source-han-serif/releases"
    echo "  思源黑体：https://github.com/adobe-fonts/source-han-sans/releases"
    echo "  霞鹜文楷：https://github.com/lxgw/LxgwWenKai/releases"
    exit 1
fi
