#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
登革病毒基因组结构示意图
DENV-2 参考株 NC_001477.1, 全长 10723 nt (坐标为示意)

输入 : features.csv, 列 = name,start,end,kind
       kind 取值: UTR / structural / nonstructural
输出 : denv_genome_map.png (300 dpi)
依赖 : matplotlib>=3.5, pandas
运行 : python plot_genome_map.py
"""

import matplotlib
matplotlib.use("Agg")  # 无显示服务器时使用 Agg 后端
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle, Patch
from matplotlib import font_manager
import pandas as pd
import os

# 中文字体: 把 NotoSansSC-Regular.ttf 与脚本放同一目录即可
_FONT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "NotoSansSC-Regular.ttf")
if os.path.exists(_FONT):
    font_manager.fontManager.addfont(_FONT)
    plt.rcParams["font.family"] = "Noto Sans SC"
plt.rcParams["axes.unicode_minus"] = False

GENOME_LEN = 10723
ACCESSION = "NC_001477.1"

# CNS 风格配色: 低饱和、色盲友好
COLORS = {
    "UTR": "#9E9E9E",            # 灰: 非翻译区
    "structural": "#D45D5C",    # 砖红: 结构蛋白 C/prM/E
    "nonstructural": "#4C78A8",  # 雾蓝: 非结构蛋白 NS1-NS5
}
KIND_LABEL = {"structural": "结构蛋白", "nonstructural": "非结构蛋白", "UTR": "非翻译区"}


def main():
    feat = pd.read_csv("features.csv")
    fig, ax = plt.subplots(figsize=(12, 3.2))
    y0, h = 0.42, 0.28

    for _, r in feat.iterrows():
        x = r["start"] - 1  # 转 0-based 绘图坐标
        w = r["end"] - r["start"] + 1
        ax.add_patch(Rectangle((x, y0), w, h, facecolor=COLORS[r["kind"]],
                               edgecolor="white", linewidth=1.2))
        cx = x + w / 2
        if w < 300:  # 过短的元件(如 2K)标签引出到下方
            ax.plot([cx, cx], [y0, y0 - 0.04], color="black", lw=0.8)
            ax.text(cx, y0 - 0.06, r["name"], ha="center", va="top", fontsize=7)
        else:
            ax.text(cx, y0 + h / 2, r["name"], ha="center", va="center",
                    fontsize=8, color="white", weight="bold")

    # 基因组标尺
    ax.set_xlim(-150, GENOME_LEN + 50)
    ax.set_ylim(0, 1.15)
    ax.set_xticks(range(0, GENOME_LEN + 1, 2000))
    ax.set_xlabel("基因组坐标 (nt)", fontsize=10)
    ax.set_yticks([])
    for spine in ("top", "right", "left"):
        ax.spines[spine].set_visible(False)
    ax.spines["bottom"].set_linewidth(1.0)
    ax.tick_params(axis="x", labelsize=8)

    # 图例: 放在坐标轴内部上方空白处, 避免与标题重叠
    handles = [Patch(facecolor=COLORS[k], label=KIND_LABEL[k])
               for k in ("structural", "nonstructural", "UTR")]
    ax.legend(handles=handles, loc="upper center", bbox_to_anchor=(0.5, 0.97),
              ncol=3, frameon=False, fontsize=9)

    ax.set_title(f"登革病毒基因组结构示意图 (DENV-2, {ACCESSION}, {GENOME_LEN} nt)",
                 fontsize=12, weight="bold", pad=12)
    fig.tight_layout()
    fig.savefig("denv_genome_map.png", dpi=300, bbox_inches="tight")
    print("saved denv_genome_map.png")


if __name__ == "__main__":
    main()
