# -*- coding: utf-8 -*-
"""fig_common.py —— 全书教学图共享配置：中文字体、统一配色、保存函数。"""
import matplotlib
matplotlib.use("Agg")
from matplotlib import font_manager
import matplotlib.pyplot as plt
import os

# ---- 注册中文字体（Windows 常见字体，按优先级） ----
_FONT_CANDIDATES = [
    r"C:\Windows\Fonts\simhei.ttf",   # 黑体
    r"C:\Windows\Fonts\msyh.ttc",     # 微软雅黑
    r"C:\Windows\Fonts\simsunb.ttf",  # 宋体
]
for _fp in _FONT_CANDIDATES:
    if os.path.exists(_fp):
        try:
            font_manager.fontManager.addfont(_fp)
        except Exception:
            pass

plt.rcParams["font.sans-serif"] = ["SimHei", "Microsoft YaHei", "SimSun", "DejaVu Sans"]
plt.rcParams["axes.unicode_minus"] = False
plt.rcParams["font.size"] = 11
plt.rcParams["axes.titlesize"] = 13
plt.rcParams["axes.labelsize"] = 11
plt.rcParams["figure.dpi"] = 110
plt.rcParams["savefig.dpi"] = 200

# ---- 统一配色 ----
# 生态位配色（全书一致）
NICHE_COLORS = {
    "肿瘤核心": "#C0392B",   # 深红
    "侵袭前沿": "#E67E22",   # 橙
    "免疫浸润区": "#27AE60",  # 绿
    "基质区": "#2980B9",     # 蓝
}
# 细胞类型配色（全书一致）
CT_COLORS = {
    "肿瘤细胞": "#C0392B",
    "CAF": "#8E44AD",
    "CD8 T": "#2980B9",
    "巨噬细胞": "#27AE60",
    "B 细胞": "#F39C12",
    "内皮细胞": "#16A085",
    "NK": "#5D6D7E",
}
# 通用分类色板
PALETTE10 = ["#C0392B", "#E67E22", "#27AE60", "#2980B9", "#8E44AD",
             "#16A085", "#F39C12", "#7F8C8D", "#E74C3C", "#2C3E50"]

FIG_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "figures")


def savefig(fig, name, **kw):
    """保存图到 figures/ 目录（自动创建目录）。"""
    os.makedirs(FIG_DIR, exist_ok=True)
    path = os.path.join(FIG_DIR, name)
    fig.savefig(path, bbox_inches="tight", facecolor="white", **kw)
    plt.close(fig)
    print("saved:", os.path.basename(path), f"{os.path.getsize(path)/1024:.0f} KB")
    return path
