# =============================================================================
# Snakefile — sRNA-TAPS pipeline
# Profile-based SLURM submission (no --cluster string needed).
# Run via: snakemake --profile profile/
#      or: bash sRNA_taps.bash   (from project directory)
#
# Project structure expected in the working directory (e.g. sRNA_TAPS_bio/):
#   config.yaml          — project config
#   rawfiles/            — *.merged.fq.gz input FASTQs
#   04a.genome/          — reference FASTA + GTF + Bowtie1 index
#   samples.tsv          — sample sheet (sample, condition, cell_line, fastq)
# =============================================================================

import pandas as pd

import os
from srnataps.utils import normalize_condition
from srnataps.species import resolve_reference_config

# ── Dynamic memory estimation ──────────────────────────────────────────────────
def est_mem(base_mb, *input_paths, scale=10, floor_mb=2000, ceil_mb=128000):
    """
    Estimate SLURM memory (MB) from input file sizes.

    base_mb      : fixed tool overhead (index loading, Python runtime, etc.)
    *input_paths : one or more input file paths to measure
    scale        : additional MB per MB of input data
    floor_mb     : minimum memory — never request less than this
    ceil_mb      : hard cap — protects against unexpectedly large files

    Users tune globally in config.yaml:
        resources:
          mem_scale_factor: 1.5   # request 50% more memory on restrictive clusters
    """
    user_factor = float(config.get("resources", {}).get("mem_scale_factor", 1.0))
    total_mb = 0.0
    for p in input_paths:
        try:
            total_mb += os.path.getsize(str(p)) / (1024 * 1024)
        except (OSError, TypeError, ValueError):
            pass
    estimated = int((base_mb + total_mb * scale) * user_factor)
    return max(floor_mb, min(ceil_mb, estimated))
# ──────────────────────────────────────────────────────────────────────────────

from pathlib import Path

configfile: "config.yaml"

# ── Sample sheet ──────────────────────────────────────────────────────────────
SAMPLES_DF = pd.read_csv("samples.tsv", sep="\t").set_index("sample")
SAMPLES_DF["condition_raw"] = SAMPLES_DF["condition"]
SAMPLES_DF["condition"] = SAMPLES_DF["condition"].map(
    lambda c: normalize_condition(c, strict=True)
)
SAMPLES     = SAMPLES_DF.index.tolist()

# Optional sample filter (set by `srnataps module --sample a,b,c`). Subsets
# SAMPLES before any expand() so every downstream target restricts to the
# named samples. Errors clearly if a requested sample isn't in the sheet.
_sample_filter = config.get("sample_filter")
if _sample_filter:
    _wanted  = [s.strip() for s in str(_sample_filter).split(",") if s.strip()]
    _missing = [s for s in _wanted if s not in SAMPLES]
    if _missing:
        raise ValueError(
            "--sample: not in samples.tsv: " + ", ".join(_missing) +
            "\n  Available samples: " + ", ".join(SAMPLES)
        )
    SAMPLES = _wanted
    print(f"[srnataps] sample filter active — running {len(SAMPLES)} sample(s): "
          + ", ".join(SAMPLES))
CELL_LINES  = SAMPLES_DF.loc[SAMPLES, "cell_line"].unique().tolist()
BIOTYPES    = ["rRNA", "miRNA", "tRNA", "snoRNA", "snRNA", "piRNA", "lncRNA", "other"]

# ── Directory layout (from config) ───────────────────────────────────────────
OUTDIR      = Path(config["project"]["outdir"])
QC_DIR      = OUTDIR / config["output"]["fastqc"]
TRIM_DIR    = OUTDIR / config["output"]["trimmed"]
GENOME_DIR  = OUTDIR / config["output"]["genome"]
REFERENCE_DETAILS = resolve_reference_config(config["reference"], GENOME_DIR)
ALIGN_DIR   = OUTDIR / config["output"]["aligned"]
BIOTYPE_DIR = OUTDIR / config["output"]["biotypes"]
SNP_DIR     = OUTDIR / config["output"]["snp"]
CALLS_DIR   = OUTDIR / config["output"]["calls"]
POOLED_DIR  = OUTDIR / config["output"].get("pooled_calls", "07b.pooled_calls")
CONTRAST_DIR = OUTDIR / config["output"].get("control_contrast", "07c.control_contrast")
REPLICATE_DIR = OUTDIR / config["output"].get("replicate_calls", "07d.replicate_calls")
STRINGENT_DIR = OUTDIR / config["output"].get("stringent_calls", "07e.stringent_calls")
EVIDENCE_AUDIT_DIR = OUTDIR / config["output"].get("evidence_audit", "10.evidence_audit")
UMAP_DIR    = OUTDIR / config["output"].get("umap", "07a.umap")
BENCH_DIR   = OUTDIR / config["output"]["benchmark"]
COMPARE_DIR = OUTDIR / config["output"]["compare"]
LOG_DIR     = OUTDIR / config["output"]["logs"]
REPORT_DIR  = OUTDIR / config["output"].get("report", "report")

# ── Helper: cell line from sample name ───────────────────────────────────────
def get_cell_line(sample):
    return SAMPLES_DF.loc[sample, "cell_line"]

def get_condition(sample):
    return SAMPLES_DF.loc[sample, "condition"]

def get_notreat_bams(wc):
    notreat = SAMPLES_DF[
        (SAMPLES_DF["condition"] == "no_treat") &
        (SAMPLES_DF["cell_line"] == wc.cell_line)
    ].index.tolist()
    if not notreat:
        raise ValueError(
            f"No no_treat samples found for cell_line={wc.cell_line}. "
            "Accepted no-treatment labels include no_treat, no-treat, "
            "notreat, untreated, and untr."
        )
    return [str(ALIGN_DIR / f"{s}.sorted.bam") for s in notreat]

def get_snp_bed(wc):
    cl = get_cell_line(wc.sample)
    return str(SNP_DIR / f"sample_snps_{cl}.bed")

def get_min_cov(wc):
    return {
        "rRNA": 10, "miRNA": 3, "tRNA": 3,
        "snoRNA": 3, "snRNA": 5, "piRNA": 5,
        "lncRNA": 5, "other": 5,
    }.get(wc.biotype, 5)

CONDITION_CONFIG = config.get("condition_analysis", {})
CONDITION_ANALYSIS_ENABLED = bool(CONDITION_CONFIG.get("enabled", False))
CONDITIONS = ["treat", "pb_ctrl", "no_treat"]

def condition_samples(cell_line, condition):
    selected = SAMPLES_DF[
        (SAMPLES_DF["cell_line"] == cell_line)
        & (SAMPLES_DF["condition"] == condition)
    ].index.tolist()
    if not selected:
        raise ValueError(
            f"Condition analysis requires {condition} samples for "
            f"cell_line={cell_line}"
        )
    return selected

def condition_biotype_bams(wc):
    return [
        str(BIOTYPE_DIR / wc.biotype / f"{sample}_{wc.biotype}.sorted.bam")
        for sample in condition_samples(wc.cell_line, wc.condition)
    ]

def all_biotype_bams(wc):
    return [
        str(BIOTYPE_DIR / wc.biotype / f"{sample}_{wc.biotype}.sorted.bam")
        for sample in SAMPLES
        if get_cell_line(sample) == wc.cell_line
    ]

# ── Include rules ─────────────────────────────────────────────────────────────
include: "rules/qc.smk"
include: "rules/trim.smk"
include: "rules/align.smk"
include: "rules/biotype.smk"
include: "rules/snp.smk"
include: "rules/call.smk"
include: "rules/condition.smk"
include: "rules/annotate.smk"
include: "rules/benchmark.smk"
include: "rules/compare.smk"
include: "rules/multiqc.smk"
include: "rules/report.smk"
include: "rules/umap.smk"

# ── Target rules ──────────────────────────────────────────────────────────────
rule all:
    """Full pipeline without benchmarking."""
    input:
        # FastQC pre/post trim
        expand(str(QC_DIR / "pre_trim"  / "{sample}_fastqc.html"), sample=SAMPLES),
        expand(str(QC_DIR / "post_trim" / "{sample}_trimmed_fastqc.html"), sample=SAMPLES),
        # Aligned BAMs
        expand(str(ALIGN_DIR / "{sample}.sorted.bam"), sample=SAMPLES),
        # Biotype BAMs
        expand(str(BIOTYPE_DIR / "{biotype}" / "{sample}_{biotype}.sorted.bam"),
               sample=SAMPLES, biotype=BIOTYPES),
        # SNP resources
        expand(str(SNP_DIR / "sample_snps_{cell_line}.bed"), cell_line=CELL_LINES),
        # TAPS calls
        expand(str(CALLS_DIR / "{biotype}" / "{sample}_{biotype}_taps_annotated.tsv"),
               sample=SAMPLES, biotype=BIOTYPES),
        # MultiQC
        str(OUTDIR / "report" / "multiqc_report.html"),
        # R figure reports (per stage)
        str(OUTDIR / "report" / "figures" / ".report_qc.done"),
        str(OUTDIR / "report" / "figures" / ".report_biotype.done"),
        str(OUTDIR / "report" / "figures" / ".report_modification.done"),
        str(OUTDIR / "report" / "figures" / ".report_seqlogos.done"),
        str(OUTDIR / "report" / "figures" / ".report_mirna_atlas.done") if CONDITION_ANALYSIS_ENABLED else [],
        str(OUTDIR / "report" / "figures" / ".report_global_distribution.done") if CONDITION_ANALYSIS_ENABLED else [],
        expand(
            str(REPLICATE_DIR / "{biotype}" / "treat_{cell_line}_replicate_{biotype}_taps.tsv"),
            cell_line=CELL_LINES, biotype=BIOTYPES,
        ) if CONDITION_ANALYSIS_ENABLED else [],
        expand(
            str(STRINGENT_DIR / "{biotype}" / "treat_{cell_line}_stringent_{biotype}_taps.tsv"),
            cell_line=CELL_LINES, biotype=BIOTYPES,
        ) if CONDITION_ANALYSIS_ENABLED else [],
        str(REPORT_DIR / "tables" / "evidence_tier_summary.tsv") if CONDITION_ANALYSIS_ENABLED else [],

rule all_benchmark:
    """Full pipeline including benchmarking and comparison."""
    input:
        rules.all.input,
        # rastair
        expand(str(BENCH_DIR / "rastair" / "all"  / "{sample}" / "{sample}.bed.gz"), sample=SAMPLES),
        expand(str(BENCH_DIR / "rastair" / "cpg"  / "{sample}" / "{sample}.bed.gz"), sample=SAMPLES),
        # asTair
        expand(str(BENCH_DIR / "astair" / "{biotype}" / ".done_{sample}"),
               sample=SAMPLES, biotype=BIOTYPES),
        # Bismark
        expand(str(BENCH_DIR / "bismark" / "{sample}" / ".done"), sample=SAMPLES),
        # Comparison
        str(COMPARE_DIR / "concordance_summary.tsv"),
        str(COMPARE_DIR / "correlation_summary.tsv"),
        # Benchmark R figures
        str(OUTDIR / "report" / "figures" / ".report_benchmark.done"),


# ── Per-module aggregator targets (used by `srnataps module <name>`) ──────────
# Each requests the output file set for one pipeline stage, letting Snakemake
# resolve the underlying rules. Names match the rule_map in srnataps/cli.py.

rule module_fastqc:
    """Stage target: FastQC (pre + post trim) for all samples."""
    input:
        expand(str(QC_DIR / "pre_trim"  / "{sample}_fastqc.html"), sample=SAMPLES),
        expand(str(QC_DIR / "post_trim" / "{sample}_trimmed_fastqc.html"), sample=SAMPLES),

rule module_trim:
    """Stage target: adapter-trimmed FASTQs for all samples."""
    input:
        expand(str(TRIM_DIR / "{sample}_trimmed.fq.gz"), sample=SAMPLES),

rule module_index:
    """Stage target: genome FASTA index + Bowtie1 index."""
    input:
        config["reference"]["genome_fa"] + ".fai",
        alignment_index_markers(None),

rule module_align:
    """Stage target: sorted BAMs for all samples."""
    input:
        expand(str(ALIGN_DIR / "{sample}.sorted.bam"), sample=SAMPLES),

rule module_biotype:
    """Stage target: per-biotype split BAMs for all samples."""
    input:
        expand(str(BIOTYPE_DIR / "{biotype}" / "{sample}_{biotype}.sorted.bam"),
               sample=SAMPLES, biotype=BIOTYPES),

rule module_snp:
    """Stage target: per-cell-line SNP blacklists."""
    input:
        expand(str(SNP_DIR / "sample_snps_{cell_line}.bed"), cell_line=CELL_LINES),

rule module_call:
    """Stage target: annotated TAPS calls for all samples/biotypes."""
    input:
        expand(str(CALLS_DIR / "{biotype}" / "{sample}_{biotype}_taps_annotated.tsv"),
               sample=SAMPLES, biotype=BIOTYPES),

rule module_condition:
    """Stage target: pooled, replicate-supported, and stringent condition calls."""
    input:
        expand(
            str(POOLED_DIR / "{biotype}" / "{condition}_{cell_line}_pooled_{biotype}_taps.tsv"),
            condition=CONDITIONS, cell_line=CELL_LINES, biotype=BIOTYPES,
        ),
        expand(
            str(REPLICATE_DIR / "{biotype}" / "treat_{cell_line}_replicate_{biotype}_taps.tsv"),
            cell_line=CELL_LINES, biotype=BIOTYPES,
        ),
        expand(
            str(STRINGENT_DIR / "{biotype}" / "treat_{cell_line}_stringent_{biotype}_taps.tsv"),
            cell_line=CELL_LINES, biotype=BIOTYPES,
        ),
        str(REPORT_DIR / "tables" / "evidence_tier_summary.tsv"),

rule module_benchmark:
    """Stage target: rastair (all+cpg), asTair, and Bismark outputs."""
    input:
        expand(str(BENCH_DIR / "rastair" / "all" / "{sample}" / "{sample}.bed.gz"), sample=SAMPLES),
        expand(str(BENCH_DIR / "rastair" / "cpg" / "{sample}" / "{sample}.bed.gz"), sample=SAMPLES),
        expand(str(BENCH_DIR / "astair" / "{biotype}" / ".done_{sample}"),
               sample=SAMPLES, biotype=BIOTYPES),
        expand(str(BENCH_DIR / "bismark" / "{sample}" / ".done"), sample=SAMPLES),

rule module_compare:
    """Stage target: concordance + correlation summaries."""
    input:
        str(COMPARE_DIR / "concordance_summary.tsv"),
        str(COMPARE_DIR / "correlation_summary.tsv"),


rule module_umap:
    """Stage target: UMAP dimensionality reduction and cluster analysis."""
    input:
        str(UMAP_DIR / "umap_coordinates.tsv"),
        str(UMAP_DIR / "outlier_classification.tsv"),
        str(UMAP_DIR / "neighbors.json"),
        str(UMAP_DIR / "pb_tet_comparison" / "umap_coordinates.tsv"),
        str(UMAP_DIR / "pb_tet_comparison" / "condition_statistics.tsv"),
