# =========================
# 02 从标准化 GWAS 文件提取原始共定位区域
# =========================

source("R/config.R")
source("R/utils.R")

loci <- read_loci_file()
summary_list <- list()

for (i in seq_len(nrow(loci))) {
  row <- loci[i]
  gene <- row$Gene
  protein_id <- row$Protein_ID
  outcome <- row$Outcome
  outcome_id <- row$Outcome_ID %||% NA_character_
  chr <- as.integer(row$chr)
  region_start <- as.integer(row$region_start)
  region_end <- as.integer(row$region_end)

  gwas_file <- GWAS_STANDARDIZED_FILES[[outcome]]
  if (is.null(gwas_file)) stop("No standardized GWAS file configured for outcome: ", outcome)

  gwas_raw <- read_any_tsv(gwas_file)
  gwas <- standardise_gwas(gwas_raw)

  gwas_region <- gwas[
    chr_gwas == chr &
      pos_gwas >= region_start &
      pos_gwas <= region_end
  ]

  gwas_region[, Gene := gene]
  gwas_region[, Protein_ID := protein_id]
  gwas_region[, Outcome := outcome]
  gwas_region[, Outcome_ID := outcome_id]
  gwas_region[, region_chr := chr]
  gwas_region[, region_start := region_start]
  gwas_region[, region_end := region_end]

  out_file <- file.path(DIR_GWAS_REGIONS, paste0(gene, "_", outcome, "_GWAS_original_region.tsv.gz"))
  data.table::fwrite(gwas_region, out_file, sep = "\t")

  summary_list[[length(summary_list) + 1]] <- data.frame(
    Gene = gene,
    Protein_ID = protein_id,
    Outcome = outcome,
    Outcome_ID = outcome_id,
    chr = chr,
    region_start = region_start,
    region_end = region_end,
    GWAS_SNPs_in_region = nrow(gwas_region),
    Output_file = out_file,
    stringsAsFactors = FALSE
  )

  cat("GWAS region extracted:", gene, outcome, nrow(gwas_region), "\n")
}

gwas_summary <- data.table::rbindlist(summary_list, fill = TRUE)
openxlsx::write.xlsx(
  gwas_summary,
  file.path(DIR_TABLES, "original_loci_GWAS_region_extraction_summary.xlsx"),
  overwrite = TRUE
)

write_status("02_extract_gwas_regions", TRUE, "GWAS regional files and summary generated.")
