#!/usr/bin/env Rscript

suppressPackageStartupMessages({
  library(data.table)
  library(ggplot2)
})

args <- commandArgs(trailingOnly = TRUE)
if (length(args) < 1) stop("Usage: plot_Fig2D_dotplot_fixedTop10.R /path/to/Panel_D")

panel_d <- args[1]
setDTthreads(threads = 8)

infile <- file.path(panel_d, "outputs", "Fig2D_fixedTop10_subfamily_copycount_within_family.tsv")
toplist <- file.path(panel_d, "inputs", "top10_subfamilies_from_pie.txt")
outfile <- file.path(panel_d, "outputs", "Fig2D_dotplot_fixedTop10_within_family_copycount.pdf")

dt <- fread(infile, header = FALSE)
setnames(dt, c("subfamily","class","family","subfamily_count","family_total_count","pct_within_family"))

# enforce the exact order you want (top -> bottom)
ord <- fread(toplist, header = FALSE)[[1]]
dt[, subfamily := factor(subfamily, levels = rev(ord))]  # rev so first appears at top

p <- ggplot(dt, aes(x = pct_within_family, y = subfamily)) +
  geom_point(aes(size = subfamily_count, color = family), alpha = 0.9) +
  scale_size_continuous(name = "Subfamily copy count\n(in LR-only)") +
  labs(
    x = "Percent of TE copies within the same family (in LR-only region) (%)",
    y = "TE subfamily (fixed Top 10 from bp-based pie)",
    title = "Top 10 TE subfamilies (bp-ranked) — copy-count composition within family",
    subtitle = "X = (# copies of subfamily) / (# total copies in same family), within LR-only region"
  ) +
  theme_bw(base_size = 13) +
  theme(
    plot.title = element_text(face = "bold"),
    axis.title = element_text(face = "bold"),
    legend.title = element_text(face = "bold")
  )

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