# 加载所需的包
suppressPackageStartupMessages(library(circlize))
suppressPackageStartupMessages(library(RColorBrewer))
suppressPackageStartupMessages(library(ComplexHeatmap))
suppressPackageStartupMessages(library(dendextend))

# 获取命令行参数
args <- commandArgs(trailingOnly = TRUE)

# 检查参数数量
if (length(args) != 2) {
  stop("请提供两个参数:输入CSV文件路径和输出PDF文件路径。", call. = FALSE)
}

# 获取输入CSV文件路径和输出PDF文件路径
input_csv <- args[1]
output_pdf <- args[2]

# 检查输入文件是否存在
if (!file.exists(input_csv)) {
  stop("输入文件不存在。请检查文件路径。", call. = FALSE)
}

# 函数加载和预处理数据
load_and_preprocess_data <- function(file_path) {
  data <- read.table(file = file_path, header = TRUE, row.names = 1, sep = ',')
  data_matrix <- as.matrix(data)
  normalized_data <- t(scale(t(data_matrix)))
  normalized_data[is.na(normalized_data)] <- 0
  return(normalized_data)
}

# 加载和预处理数据
cir1 <- load_and_preprocess_data(input_csv)

# 打印数据维度和头部
print(dim(cir1))
print(head(cir1))

# 定义颜色梯度
mycol <- colorRamp2(c(-2.5, 0.3, 3.1), c("blue", "white", "red"))

# 打开PDF设备,设置宽度和高度相等
pdf(output_pdf, width = 8, height = 8)

# 设置绘图参数
circos.par(gap.after = c(30))

# 绘制调整后的圆形热图
circos.heatmap(cir1, 
                col = mycol, 
                dend.side = "inside", 
                rownames.side = "outside", 
                rownames.col = "black", 
                rownames.cex = 1.3, 
                track.height = 0.35,  # 增加轨道高度
                cluster = TRUE, 
                dend.track.height = 0.18, 
                dend.callback = function(dend, m, si) {
                  color_branches(dend, k = 15, col = 1:15)
                })

# 添加列名
circos.track(track.index = get.current.track.index(), panel.fun = function(x, y) {
  if (CELL_META$sector.numeric.index == 1) {
    cn <- colnames(cir1)
    n <- length(cn)
    circos.text(rep(CELL_META$cell.xlim[2], n) + convert_x(0.5, "mm"), 
                1:n + 2.5, 
                cn, cex = 1.0, adj = c(0, 0.5), facing = "inside")  # 将 cex 从 0.6 改为 1.0
  }
}, bg.border = NA)

# 添加图例
lg <- Legend(title = "Exp", col_fun = mycol, direction = "vertical")
grid.draw(lg)

# 清除圆形图
circos.clear()

# 关闭PDF设备
dev.off()

message(output_pdf)