#!/bin/bash
cd "$(dirname "$0")"

LOGFILE="run_analysis_$(date '+%Y%m%d_%H%M%S').log"
exec > >(tee -a "$LOGFILE") 2>&1

echo "======================================================"
echo "Run started: $(date)"
echo "Working dir: $(pwd)"
echo "======================================================"

TSS="../Li_adt/BPA/BPA_female/gencode_mm10_gene_TSS_pc_lncRNA.sorted.bed"

# ─────────────────────────────────────────────────────
# Step 1: Annotate OCR_adt_br.txt with Direction column
# OCR cols: OCR(1) logFC(2) logCPM(3) PValue(4) FDR(5)
#           DAR(6) Tissue(7) Age(8) Sex(9) Exposure(10) Lab(11)
# ─────────────────────────────────────────────────────
awk -F'\t' 'BEGIN{OFS="\t"}
  NR==1 { print $0, "Direction"; next }
  $2 > 0 { print $0, "UP"; next }
           { print $0, "DOWN" }
' OCR_adt_br.txt > OCR_adt_br_annotated.txt

echo "Step 1 done: OCR_adt_br_annotated.txt"

# ─────────────────────────────────────────────────────
# Steps 2–6: Loop over 4 sex × dose combinations
# ─────────────────────────────────────────────────────
declare -A DEGSEX=( [F]="Female" [M]="Male" )

for SEX in F M; do
  for DOSE in BPA10mg BPA10ug; do
    TAG="${SEX}_${DOSE}"
    DEGSEX_VAL="${DEGSEX[$SEX]}"

    # ── Step 2: Extract table (DAR=TRUE, both directions) ──
    # annotated cols: OCR(1) logFC(2) logCPM(3) PValue(4) FDR(5)
    #                 DAR(6) Tissue(7) Age(8) Sex(9) Exposure(10) Lab(11) Direction(12)
    awk -F'\t' -v sex="$SEX" -v dose="$DOSE" 'BEGIN{OFS="\t"}
      NR==1 || ($6=="TRUE" && $9==sex && $10==dose)
    ' OCR_adt_br_annotated.txt > "OCR_adt_br_DAR_${TAG}.txt"
    echo "Extracted: OCR_adt_br_DAR_${TAG}.txt ($(tail -n +2 "OCR_adt_br_DAR_${TAG}.txt" | wc -l) rows)"

    # ── Step 3 & 4: Make sorted bed + bedtools closest ──
    for DIR in UP DOWN; do
      BEDFILE="OCR_adt_br_DAR_${TAG}_${DIR}.sorted.bed"
      NEAREST="OCR_adt_br_DAR_${TAG}_${DIR}_nearestGene.txt"
      FINAL="OCR_adt_br_DAR_${TAG}_${DIR}_DEG.txt"

      # bed cols: chr(1) start(2) end(3) Direction(4) logFC(5) logCPM(6)
      #           PValue(7) FDR(8) DAR(9) Tissue(10) Age(11) Sex(12) Exposure(13) Lab(14)
      awk -F'\t' -v dir="$DIR" 'BEGIN{OFS="\t"}
        NR>1 && $12==dir {
          split($1, a, ",")
          print a[1], a[2], a[3], $12, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11
        }
      ' "OCR_adt_br_DAR_${TAG}.txt" \
      | sort -k1,1 -k2,2n \
      > "$BEDFILE"
      echo "BED: $BEDFILE ($(wc -l < "$BEDFILE") peaks)"

      # bedtools closest; filter ±1 Mb; add header
      # output cols 1-14: peak fields; cols 15-21: TSS fields; col 22: dist
      {
        printf "chr\tstart\tend\tDirection\tlogFC\tlogCPM\tPValue\tFDR\tDAR\tTissue\tAge\tSex\tExposure\tLab"
        printf "\ttss_chr\ttss_start\ttss_end\tgene_id\tgene_name\tgene_type\tstrand\tdist_to_TSS\n"
        bedtools closest \
          -a "$BEDFILE" \
          -b "$TSS" \
          -D a \
          -k 1 \
          -sorted \
        | awk 'BEGIN{OFS="\t"} $NF != "." && ($NF <= 1000000 && $NF >= -1000000)'
      } > "$NEAREST"
      echo "Nearest: $NEAREST ($(tail -n +2 "$NEAREST" | wc -l) hits)"

      # ── Step 5 & 6: Join nearest genes with DEG (same sex + same dose) ──
      # DEG cols: baseMean(1) log2FoldChange(2) lfcSE(3) stat(4) pvalue(5) padj(6)
      #           cond1(7) cond2(8) gene(9) lab(10) type(11) sig(12) direction(13)
      #           group(14) tissue(15) stage(16) sex(17)
      # Join: gene_name (nearest col 19) == gene (DEG col 9)
      # Sex match: DEG col 17 == "Female"/"Male"; Dose match: cond1 contains dose string
      awk -F'\t' -v degsex="$DEGSEX_VAL" -v dose="$DOSE" 'BEGIN{OFS="\t"}
        NR==FNR {
          if (FNR==1) { deg_header=$0; next }
          if ($17==degsex && index($7, dose)>0) {
            key = $9
            deg_count[key]++
            deg_rows[key, deg_count[key]] = $0
          }
          next
        }
        FNR==1 { print $0, deg_header; next }
        $19 in deg_count {
          for (i=1; i<=deg_count[$19]; i++)
            print $0, deg_rows[$19, i]
        }
      ' DEG_adt_br.txt "$NEAREST" > "$FINAL"
      echo "Final: $FINAL ($(tail -n +2 "$FINAL" | wc -l) rows)"
    done
  done
done

echo ""
echo "============================================="
echo "All steps completed successfully!"
echo "Finished: $(date)"
echo "Log saved to: $LOGFILE"
echo "============================================="
