#!/usr/bin/env Rscript

suppressPackageStartupMessages({
  library(data.table)
})

setDTthreads(8)

# =========================
# INPUT / OUTPUT
# =========================

te_file <- "/BLUES/eric/ONT/hg38_TE_noY.bed.gz"

outdir <- "/BLUES/eric/ONT_WGBS/Figure_3/Volcano_plot/input"
dir.create(outdir, recursive = TRUE, showWarnings = FALSE)

outfile <- file.path(outdir, "TE_subfamily_stats.tsv")

# =========================
# LOAD
# =========================

te <- fread(
  cmd = paste("zcat", te_file),
  sep = "\t",
  header = FALSE,
  showProgress = TRUE
)

cat("Loaded", nrow(te), "TE entries\n")

# =========================
# COLUMN NAMES
# =========================

setnames(
  te,
  c("chr", "start", "end", "strand", "annotation")
)

# =========================
# PARSE ANNOTATION
# =========================

te[, subfamily := sub(
  '.*repeat_id "([^,]+),.*',
  '\\1',
  annotation
)]

te[, class := sub(
  '.*repeat_class "([^"]+)".*',
  '\\1',
  annotation
)]

te[, family := sub(
  '.*repeat_family "([^"]+)".*',
  '\\1',
  annotation
)]

# =========================
# CLEAN
# =========================

te <- te[
  !is.na(subfamily) &
  subfamily != "" &
  subfamily != "."
]

te[, length_bp := end - start]

te <- te[length_bp > 0]

# =========================
# SUMMARIZE
# =========================

stats <- te[
  ,
  .(
    copies = .N,
    total_length = sum(length_bp)
  ),
  by = .(subfamily, class, family)
]

# =========================
# SORT
# =========================

setorder(stats, -copies)

# =========================
# SAVE
# =========================

fwrite(
  stats,
  outfile,
  sep = "\t",
  quote = FALSE
)

cat("Saved:", outfile, "\n")
cat("Total subfamilies:", nrow(stats), "\n")

# =========================
# PREVIEW
# =========================

print(head(stats))