#!/usr/bin/env Rscript
# 登革病毒基因组结构示意图 (R + ggplot2 版)
# DENV-2 参考株 NC_001477.1, 全长 10723 nt (坐标为示意)
#
# 输入: features.csv, 列 = name,start,end,kind
#       kind 取值: UTR / structural / nonstructural
# 输出: denv_genome_map_r.png (300 dpi)
# 依赖: ggplot2, ragg, systemfonts
#       conda 安装: conda install -c conda-forge r-ggplot2 r-ragg
# 运行: Rscript plot_genome_map.R
# 中文字体: NotoSansSC-Regular.ttf 与脚本放同一目录即可;
#           关键: R 必须运行在 UTF-8 locale 下, 否则中文会被按字节渲染成点
#           (本脚本开头已自动切换, 仍失败请手动执行 Sys.setlocale("LC_ALL","C.utf8"))

# --- 关键: 切到 UTF-8 locale, 否则 C locale 下中文字符串按字节处理 ---
try(invisible(Sys.setlocale("LC_ALL", "C.utf8")), silent = TRUE)

suppressPackageStartupMessages({
  library(ggplot2)
  library(ragg)
  library(systemfonts)
})

GENOME_LEN <- 10723

# 注册随附的中文字体
register_font("NotoSC", "NotoSansSC-Regular.ttf")

feat <- read.csv("features.csv", stringsAsFactors = FALSE)
feat$kind <- factor(feat$kind, levels = c("structural", "nonstructural", "UTR"))
feat$len <- feat$end - feat$start + 1
feat$cx <- (feat$start + feat$end) / 2

pal <- c(structural = "#D45D5C", nonstructural = "#4C78A8", UTR = "#9E9E9E")
lab <- c(structural = "结构蛋白", nonstructural = "非结构蛋白", UTR = "非翻译区")

p <- ggplot(feat) +
  geom_rect(aes(xmin = start, xmax = end + 1, ymin = 0.42, ymax = 0.70, fill = kind),
            color = "white", linewidth = 1) +
  # 块内标签 (过短元件 2K 除外)
  geom_text(data = subset(feat, len >= 300),
            aes(x = cx, y = 0.56, label = name),
            color = "white", fontface = "bold", size = 3.2, family = "NotoSC") +
  # 过短元件标签引出到下方
  geom_segment(data = subset(feat, len < 300),
               aes(x = cx, xend = cx, y = 0.34, yend = 0.42), linewidth = 0.4) +
  geom_text(data = subset(feat, len < 300),
            aes(x = cx, y = 0.30, label = name), size = 2.8, family = "NotoSC") +
  scale_x_continuous(limits = c(-150, GENOME_LEN + 50),
                     breaks = seq(0, GENOME_LEN, 2000),
                     name = "基因组坐标 (nt)", expand = c(0, 0)) +
  scale_y_continuous(limits = c(0, 1.15)) +
  scale_fill_manual(values = pal, labels = lab, name = NULL) +
  labs(title = "登革病毒基因组结构示意图 (DENV-2, NC_001477.1, 10723 nt)") +
  theme_minimal(base_size = 11) +
  theme(
    text = element_text(family = "NotoSC"),
    axis.title.y = element_blank(),
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank(),
    panel.grid = element_blank(),
    legend.position = "top",
    plot.title = element_text(face = "bold", hjust = 0.5, margin = margin(b = 8))
  )

# 用 ragg 输出, 中文渲染稳定
agg_png("denv_genome_map_r.png", width = 12, height = 3.2, units = "in", res = 300)
print(p)
dev.off()
message("saved denv_genome_map_r.png")
