# FigS_GSE210086_overlap.R
# Cross-dataset validation: NAT10 KD RNA-seq (Dalhat 2022, GSE210086)
# vs. Spaceflight NAT10-correlated gene signature (this study)
#
# Purpose: Show that cholesterol/lipid metabolic pathways are consistently
# downregulated upon NAT10 depletion across independent datasets/cell types,
# and that spaceflight NAT10-correlated genes are enriched among genes
# down-regulated by NAT10 KD.
#
# Data: Dalhat MH et al. Clin Transl Med. 2022. PMID: 36149760
#       GEO: GSE210086 (NAT10 siRNA in MCF7 cells, n=3/group)
#       Supplementary: GSE210086_gene_count.xls (raw counts, DESeq2-ready)

suppressPackageStartupMessages({
  library(DESeq2)
  library(clusterProfiler)
  library(org.Hs.eg.db)
  library(enrichplot)
  library(msigdbr)
  library(ggplot2)
  library(patchwork)
  library(dplyr)
  library(readr)
  library(tibble)
  library(readxl)
})

OUT     <- "/Users/kurimoto/NGS/Astro/figures/panels"
GEO_DIR <- "/Users/kurimoto/NGS/Astro/rawdata/GSE210086"
dir.create(OUT, showWarnings = FALSE, recursive = TRUE)

# ── shared theme ──────────────────────────────────────────────────────────────
theme_pub <- theme_classic(base_size = 22) +
  theme(
    axis.text        = element_text(size = 19, color = "black"),
    axis.title       = element_text(size = 20),
    legend.text      = element_text(size = 18),
    legend.title     = element_text(size = 18),
    plot.title       = element_text(size = 20, face = "bold"),
    strip.background = element_blank()
  )

# ═══════════════════════════════════════════════════════════════════════════════
# 1. Load count data (GSE210086_gene_count.xls)
# ═══════════════════════════════════════════════════════════════════════════════
cat("Loading GSE210086 count data...\n")
cnt_raw <- read_tsv(
  file.path(GEO_DIR, "GSE210086_gene_count.xls"),
  show_col_types = FALSE
)

# Column layout: gene_id | siNAT10_MCF2 | siNAT10_MCF3 | siC_MCF1 |
#                          siNAT10_MCF1 | siC_MCF2 | siC_MCF3 | gene_name | ...
sic_cols   <- c("siC_MCF1",   "siC_MCF2",   "siC_MCF3")
sikd_cols  <- c("siNAT10_MCF1","siNAT10_MCF2","siNAT10_MCF3")
all_sample <- c(sic_cols, sikd_cols)

# Build count matrix (integer)
counts <- cnt_raw %>%
  filter(!duplicated(gene_name), !is.na(gene_name), gene_name != "") %>%
  column_to_rownames("gene_name") %>%
  select(all_of(all_sample)) %>%
  mutate(across(everything(), as.integer))

counts <- counts[rowSums(counts) >= 10, ]   # low-count filter
cat(sprintf("Count matrix: %d genes x %d samples\n", nrow(counts), ncol(counts)))

# ═══════════════════════════════════════════════════════════════════════════════
# 2. DESeq2 differential expression
# ═══════════════════════════════════════════════════════════════════════════════
col_data <- data.frame(
  sample    = all_sample,
  condition = factor(c(rep("Ctrl",3), rep("KD",3)), levels = c("Ctrl","KD")),
  row.names = all_sample
)

dds <- DESeqDataSetFromMatrix(
  countData = counts,
  colData   = col_data,
  design    = ~ condition
)
dds <- DESeq(dds, quiet = TRUE)
res <- results(dds, contrast = c("condition","KD","Ctrl"), alpha = 0.05)

de <- as.data.frame(res) %>%
  rownames_to_column("GeneSymbol") %>%
  filter(!is.na(log2FoldChange), !is.na(padj)) %>%
  arrange(padj)

cat(sprintf("DE genes (padj<0.05): %d up, %d down\n",
            sum(de$padj < 0.05 & de$log2FoldChange > 0, na.rm=TRUE),
            sum(de$padj < 0.05 & de$log2FoldChange < 0, na.rm=TRUE)))
cat("Top downregulated:\n")
print(head(de[de$log2FoldChange < 0,], 10)[, c("GeneSymbol","log2FoldChange","padj")])

write_csv(de, file.path(GEO_DIR, "DE_table_GSE210086_DESeq2.csv"))

# ═══════════════════════════════════════════════════════════════════════════════
# 3. GSEA on Hallmark + KEGG
# ═══════════════════════════════════════════════════════════════════════════════
gene_rank <- de %>%
  filter(!is.na(log2FoldChange)) %>%
  arrange(desc(log2FoldChange)) %>%
  { setNames(.$log2FoldChange, toupper(.$GeneSymbol)) }

# MSigDB Hallmark
h_sets <- msigdbr(species = "Homo sapiens", category = "H") %>%
  select(gs_name, gene_symbol) %>%
  mutate(gene_symbol = toupper(gene_symbol))

set.seed(42)
gsea_h <- GSEA(
  geneList     = gene_rank,
  TERM2GENE    = h_sets,
  minGSSize    = 15,
  maxGSSize    = 500,
  pvalueCutoff = 0.25,
  eps          = 0,
  verbose      = FALSE
)

h_df <- as.data.frame(gsea_h) %>% arrange(NES)
cat("\n=== GSEA Hallmark (NAT10 KD, GSE210086) ===\n")
print(h_df[, c("ID","NES","pvalue","p.adjust","setSize")])
write_csv(h_df, file.path(GEO_DIR, "GSEA_Hallmark_GSE210086.csv"))

# KEGG
kegg_sets <- msigdbr(species = "Homo sapiens", category = "C2",
                     subcategory = "CP:KEGG_LEGACY") %>%
  select(gs_name, gene_symbol) %>%
  mutate(gene_symbol = toupper(gene_symbol))

gsea_k <- GSEA(
  geneList     = gene_rank,
  TERM2GENE    = kegg_sets,
  minGSSize    = 15,
  maxGSSize    = 500,
  pvalueCutoff = 0.25,
  eps          = 0,
  verbose      = FALSE
)

k_df <- as.data.frame(gsea_k) %>% arrange(NES)
metab_kw <- "CHOLESTEROL|FATTY_ACID|LIPID|STEROID|OXIDATIVE|RIBOSOM|TRANSLATION|PPAR|ADIPOGEN"
k_metab  <- k_df[grepl(metab_kw, k_df$ID, ignore.case = TRUE), ]
cat("\n=== GSEA KEGG: metabolism-related terms ===\n")
print(k_metab[, c("ID","NES","pvalue","p.adjust")])
write_csv(k_df, file.path(GEO_DIR, "GSEA_KEGG_GSE210086.csv"))

# ═══════════════════════════════════════════════════════════════════════════════
# 4. Gene overlap: Spaceflight NAT10-corr Top500 vs GSE210086 downregulated
# ═══════════════════════════════════════════════════════════════════════════════
space_top500 <- read_csv(
  "/Users/kurimoto/NGS/Astro/rawdata/NAT10_Positive_Correlation_Top500.csv",
  show_col_types = FALSE
)$GeneSymbol %>% toupper()

motif_pos <- read_tsv(
  "/Users/kurimoto/NGS/Astro/rawdata/Motif_Positive_Genes.txt",
  show_col_types = FALSE
)$GeneSymbol %>% toupper()

kd_down_sig <- de %>%
  filter(padj < 0.05, log2FoldChange < -0.5) %>%
  pull(GeneSymbol) %>% toupper()

kd_down_nom <- de %>%
  filter(pvalue < 0.05, log2FoldChange < -0.3) %>%
  pull(GeneSymbol) %>% toupper()

universe <- toupper(unique(de$GeneSymbol))

cat(sprintf("\nSpaceflight NAT10-corr Top500 (in universe): %d\n",
            sum(space_top500 %in% universe)))
cat(sprintf("GSE210086 down (padj<0.05, LFC<-0.5): %d genes\n", length(kd_down_sig)))
cat(sprintf("GSE210086 down (p<0.05, LFC<-0.3):   %d genes\n", length(kd_down_nom)))

overlap_sig <- intersect(space_top500, kd_down_sig)
overlap_nom <- intersect(space_top500, kd_down_nom)
cat(sprintf("Overlap (Top500 ∩ padj<0.05 down): %d\n", length(overlap_sig)))
cat(sprintf("Overlap (Top500 ∩ p<0.05 down):   %d\n", length(overlap_nom)))
cat("Genes:", paste(sort(overlap_sig), collapse=", "), "\n")

# Fisher test
n_univ <- length(universe)
n_sp   <- sum(space_top500 %in% universe)
n_dn   <- length(kd_down_sig)
n_both <- length(overlap_sig)
mat <- matrix(c(n_both, n_sp - n_both, n_dn - n_both,
                n_univ - n_sp - n_dn + n_both), nrow = 2)
fish <- fisher.test(mat, alternative = "greater")
cat(sprintf("Fisher (Top500 enrichment in KD-sig-down): OR=%.2f, p=%.4f\n",
            fish$estimate, fish$p.value))

# ═══════════════════════════════════════════════════════════════════════════════
# 5. Figures
# ═══════════════════════════════════════════════════════════════════════════════

# ── Panel A: GSEA dotplot (Hallmark) ─────────────────────────────────────────
plot_h <- if (nrow(h_df) > 0) {
  h_df %>%
    mutate(label = gsub("HALLMARK_", "", ID),
           label = gsub("_", " ", label),
           label = factor(label, levels = label[order(NES)])) %>%
    slice(1:min(nrow(.), 15))
} else NULL

if (!is.null(plot_h) && nrow(plot_h) > 0) {
  pA <- ggplot(plot_h, aes(x = NES, y = label, color = p.adjust, size = setSize)) +
    geom_point() +
    geom_vline(xintercept = 0, linetype = "dashed", color = "grey60") +
    scale_color_gradient(low = "#E64B35", high = "#ADB6B6",
                         name = "adj. p") +
    scale_size_continuous(range = c(3, 9), name = "Set size") +
    labs(x = "NES", y = NULL,
         title = "NAT10 KD (GSE210086)\nHallmark GSEA") +
    theme_pub +
    theme(axis.text.y = element_text(size = 13))
  ggsave(file.path(OUT, "FigS_GSE210086_GSEA_hallmark.pdf"), pA,
         width = 10, height = max(4, nrow(plot_h) * 0.45 + 1.5), device = cairo_pdf)
  ggsave(file.path(OUT, "FigS_GSE210086_GSEA_hallmark.png"), pA,
         width = 10, height = max(4, nrow(plot_h) * 0.45 + 1.5), dpi = 300)
  cat("Saved FigS_GSE210086_GSEA_hallmark\n")
} else {
  cat("No significant Hallmark terms — skipping panel A\n")
}

# ── Panel B: Overlap gene log2FC bar chart ────────────────────────────────────
if (length(overlap_nom) > 0) {
  genes_to_plot <- if (length(overlap_sig) > 0) overlap_sig else overlap_nom
  overlap_df <- de %>%
    filter(toupper(GeneSymbol) %in% genes_to_plot) %>%
    arrange(log2FoldChange) %>%
    mutate(GeneSymbol = factor(GeneSymbol, levels = GeneSymbol),
           sig_label  = case_when(
             padj < 0.001 ~ "***",
             padj < 0.01  ~ "**",
             padj < 0.05  ~ "*",
             pvalue < 0.05 ~ "†",
             TRUE          ~ ""
           ))

  pB <- ggplot(overlap_df, aes(x = GeneSymbol, y = log2FoldChange,
                                fill = log2FoldChange < 0)) +
    geom_col(color = "black", linewidth = 0.3) +
    geom_text(aes(label = sig_label,
                  y = log2FoldChange + ifelse(log2FoldChange < 0, -0.05, 0.05)),
              size = 5, hjust = ifelse(overlap_df$log2FoldChange < 0, 1, 0)) +
    geom_hline(yintercept = 0, linewidth = 0.5) +
    scale_fill_manual(values = c("TRUE" = "#4DBBD5", "FALSE" = "#E64B35"),
                      guide = "none") +
    coord_flip() +
    labs(x = NULL,
         y = "log2FC (siNAT10 / siCtrl) — GSE210086",
         title = "Spaceflight NAT10-corr genes\ndown-regulated by NAT10 KD (MCF7)") +
    theme_pub +
    theme(axis.text.y = element_text(size = 14, face = "italic"))
  h_fig <- max(4, length(genes_to_plot) * 0.4 + 1.5)
  ggsave(file.path(OUT, "FigS_GSE210086_overlap_bar.pdf"), pB,
         width = 9, height = h_fig, device = cairo_pdf)
  ggsave(file.path(OUT, "FigS_GSE210086_overlap_bar.png"), pB,
         width = 9, height = h_fig, dpi = 300)
  cat("Saved FigS_GSE210086_overlap_bar\n")
} else {
  cat("No overlapping genes to plot\n")
}

# ── Panel C: Volcano plot (GSE210086, highlight spaceflight Top500) ──────────
vol_df <- de %>%
  mutate(
    highlight = toupper(GeneSymbol) %in% space_top500,
    overlap   = toupper(GeneSymbol) %in% overlap_sig,
    neg_log10p = -log10(pmax(pvalue, 1e-100)),
    color_cat = case_when(
      overlap   ~ "Spaceflight\nTop500 (down)",
      highlight & log2FoldChange < -0.3 ~ "Spaceflight\nTop500 (other)",
      TRUE       ~ "Other"
    )
  ) %>%
  arrange(color_cat == "Other")

color_vals <- c(
  "Spaceflight\nTop500 (down)"  = "#E64B35",
  "Spaceflight\nTop500 (other)" = "#4DBBD5",
  "Other"                       = "grey80"
)

pC <- ggplot(vol_df, aes(x = log2FoldChange, y = neg_log10p,
                          color = color_cat, size = color_cat != "Other")) +
  geom_point(alpha = 0.6) +
  geom_vline(xintercept = c(-0.5, 0.5), linetype = "dashed", color = "grey50") +
  geom_hline(yintercept = -log10(0.05),  linetype = "dashed", color = "grey50") +
  scale_color_manual(values = color_vals, name = NULL) +
  scale_size_manual(values = c("TRUE" = 2.5, "FALSE" = 1), guide = "none") +
  labs(x = "log2FC (siNAT10 / siCtrl)",
       y = expression(-log[10](p-value)),
       title = "GSE210086 NAT10 KD — Volcano\n(Spaceflight Top500 highlighted)") +
  theme_pub +
  theme(legend.position = "top")

ggsave(file.path(OUT, "FigS_GSE210086_volcano.pdf"), pC,
       width = 8, height = 7, device = cairo_pdf)
ggsave(file.path(OUT, "FigS_GSE210086_volcano.png"), pC,
       width = 8, height = 7, dpi = 300)
cat("Saved FigS_GSE210086_volcano\n")

cat("\n=== Done: all FigS_GSE210086 panels saved ===\n")

# ═══════════════════════════════════════════════════════════════════════════════
# 6b. Targeted panel: FA metabolism genes (Dalhat 2022 reported) in GSE210086
# ═══════════════════════════════════════════════════════════════════════════════
fa_genes <- c("ELOVL6","SCD","ACSL1","ACSL3","ACSL4","ACADSB","ACADM","ACAT1")

fa_df <- de %>%
  filter(GeneSymbol %in% fa_genes) %>%
  mutate(
    GeneSymbol = factor(GeneSymbol, levels = rev(fa_genes)),
    sig_label  = case_when(
      padj  < 0.05 ~ "**",
      pvalue < 0.05 ~ "*",
      TRUE          ~ ""
    ),
    label_note = paste0(round(log2FoldChange, 2),
                        " (p=", signif(pvalue, 2), ")")
  )

pD <- ggplot(fa_df, aes(x = log2FoldChange, y = GeneSymbol)) +
  geom_col(fill = "#4DBBD5", color = "black", linewidth = 0.4, width = 0.65) +
  geom_vline(xintercept = 0, linewidth = 0.5) +
  geom_text(aes(x = log2FoldChange - 0.03, label = sig_label),
            hjust = 1, size = 6, color = "black") +
  scale_x_continuous(limits = c(min(fa_df$log2FoldChange) * 1.4, 0.2)) +
  labs(
    x = "log2FC (siNAT10 / siCtrl) — GSE210086",
    y = NULL,
    title = "Fatty acid metabolism genes\n(NAT10 KD, MCF7; Dalhat et al. 2022)",
    caption = "* p<0.05; ** padj<0.05 (DESeq2)"
  ) +
  theme_pub +
  theme(axis.text.y = element_text(size = 18, face = "italic"))

ggsave(file.path(OUT, "FigS_GSE210086_FA_genes.pdf"), pD,
       width = 8, height = 5, device = cairo_pdf)
ggsave(file.path(OUT, "FigS_GSE210086_FA_genes.png"), pD,
       width = 8, height = 5, dpi = 300)
cat("Saved FigS_GSE210086_FA_genes\n")
