#!/usr/bin/env Rscript
library(ggplot2)

infile <- "/BRC/yan/heart/analysis/sn_ATAC_analysis/heart_DAR_female_vs_male_RUVr_k6_filter.txt"
outfile <- "/BRC/yan/heart/analysis/sn_ATAC_analysis/DAR_chr_pie.pdf"

dar <- read.table(infile, header = TRUE, sep = "\t")

dar$chr <- sub(":.*", "", dar$peak)
dar$group <- ifelse(dar$chr == "chrX", "chrX",
             ifelse(dar$chr == "chrY", "chrY", "Other"))

counts <- as.data.frame(table(dar$group))
colnames(counts) <- c("group", "n")
counts$group <- factor(counts$group, levels = c("chrX", "chrY", "Other"))
counts <- counts[order(counts$group), ]
counts$pct <- counts$n / sum(counts$n) * 100
counts$label <- paste0(counts$group, "\n", counts$n, " (", round(counts$pct, 1), "%)")

p <- ggplot(counts, aes(x = "", y = n, fill = group)) +
  geom_col(width = 1, color = "white", linewidth = 0.5) +
  coord_polar(theta = "y") +
  geom_text(aes(label = label),
            position = position_stack(vjust = 0.5),
            size = 4, fontface = "bold") +
  scale_fill_manual(values = c(chrX = "#E64B35", chrY = "#4DBBD5", Other = "#B0B0B0")) +
  labs(title = "DAR distribution by chromosome\n(female vs male, RUVr k=6)") +
  theme_void() +
  theme(
    plot.title   = element_text(hjust = 0.5, face = "bold", size = 13),
    legend.position = "none"
  )

ggsave(outfile, p, width = 6, height = 6)
cat("Saved:", outfile, "\n")
