from snakemake.exceptions import WorkflowError
# Snakefile - records and runs the mtpipe stages (rearrangement or artifact? S. brasiliensis mtDNA)
#
# The stage scripts (00-06) stay the single source of truth; this file declares what each stage
# needs and produces, so Snakemake can (1) run only what is out of date, (2) rerun a stage when its
# script, helpers, references or upstream results change, and (3) keep a record: per-stage logs,
# benchmarks (time/memory), software versions, a DAG figure and an HTML report.
#
#   snakemake -n                                   # dry run: what would run and why
#   snakemake --cores 16                           # run everything that is out of date
#   snakemake --cores 16 --until short_reads       # stop after a stage
#   snakemake --cores 16 -R graph                  # force-rerun one stage (and its dependants)
#   snakemake --use-conda --cores 16               # build env/environment.yml automatically
#   snakemake --rulegraph | dot -Tsvg > dag.svg    # pipeline diagram
#   snakemake --summary                            # every output: date, rule, status, needs-rerun
#   snakemake --report report.html                 # self-contained record (code, runtimes, figures)
#
# Settings: threads/work dir here (or --config wd=/scratch/x threads=32); accessions and
# coordinates stay in config.sh, which every stage sources.

import os, shutil, hashlib
configfile: "config.yaml"
# Machine-specific settings (pybin, cactus_activate, extra_bin, wd) go in config.local.yaml, which git
# ignores, so the tracked config.yaml carries no personal paths. Precedence: --config > local > config.yaml.
if os.path.exists(os.path.join(workflow.basedir, "config.local.yaml")):
    configfile: os.path.join(workflow.basedir, "config.local.yaml")

PIPE = os.path.abspath(workflow.basedir)
WD = os.path.abspath(config.get("wd", f"{PIPE}/work"))
T = int(config.get("threads", 8))
DONE, LOG, BENCH = f"{WD}/done", f"{WD}/logs", f"{WD}/benchmarks"
REFS = [f"{PIPE}/refs/{x}" for x in (
    "Sbra_UFSJ_KY825190.fasta", "Sbra_VGP_CM059865.fasta", "Sbra_UFMG_NC024941.fasta",
    "Sbra_UFSJ_KY825190.bed", "Sbra_VGP_CM059865.bed", "Sbra_UFMG_NC024941.bed",
    "source_annotations.gb", "CR_repeat_unit_VGP.fasta")]
ENV = f"{PIPE}/env/environment.yml"
# Interpreter for the py/ helpers (needs biopython + mappy). Pinned so that activating the Cactus
# virtualenv for stage 06 cannot swap it for the venv's bare python.
PYBIN = config.get("pybin") or shutil.which("python3")
ROSSO = config.get("rosso_table", "")          # Rosso et al. 2018 Table S1 (.xls), for the specimen table (optional)
CACTUS = config.get("cactus_activate", "")   # path to cactus-bin-*/venv/bin/activate (stage 06)
# PYBIN reaches the stage scripts through the environment, NOT the shell string: anything inside a
# rule's shell command is part of Snakemake's code hash, so editing pybin used to rerun every rule.
os.environ["PYBIN"] = PYBIN
# Optional tools kept in their own conda envs (e.g. MITObim + MIRA 4.0.2): appended to PATH, so the
# pipeline env's tools keep priority. Not part of any shell string either.
for _b in config.get("extra_bin", []) or []:
    os.environ["PATH"] = os.environ["PATH"] + ":" + _b
# fail early, with a clear message, if the helper python lacks its modules
import subprocess
if subprocess.run([PYBIN, "-c", "import Bio, mappy"], capture_output=True).returncode != 0:
    raise WorkflowError(f"pybin={PYBIN} cannot import Bio and mappy; set pybin in config.yaml "
                        "to the mtpipe env python (e.g. ~/miniconda3/envs/mtpipe/bin/python3)")

def md5(files):
    """Content fingerprint of a stage's code/config/references. Used as a rule *param*: Snakemake
    records params, so editing any of these files reruns exactly the stages that use them, while a
    mere `touch` does not (source-file mtimes alone do not trigger reruns in Snakemake >= 8)."""
    h = hashlib.md5()
    for f in sorted(files):
        if os.path.exists(f):
            h.update(open(f, "rb").read())
    return h.hexdigest()

def py(*names):
    return [f"{PIPE}/py/{n}.py" for n in names]

def stage(script, pre=""):
    """shell command: run a stage script with WD/THREADS/PYBIN exported, log everything, mark success."""
    return (f"{pre}export WD={WD} THREADS={{threads}}; "
            f"bash {PIPE}/{script} > {{log}} 2>&1 && touch {{output.done}}")

wildcard_constraints: x = "[^/]+"

rule all:
    input:
        f"{DONE}/06_graph.done",
        f"{DONE}/06_graph_v2.done",
        f"{WD}/record/software_versions.tsv",
        f"{WD}/record/rulegraph.svg",

# ---------------------------------------------------------------------------------------------
rule fetch:
    """00 - outgroup, run tables, LARGE Illumina, VGP HiFi, nuclear reference (network)."""
    input:  f"{PIPE}/00_fetch.sh", f"{PIPE}/config.sh"
    output: done=f"{DONE}/00_fetch.done",
            outgroup=f"{WD}/00_data/ref/outgroup.fasta"
    params: fingerprint=md5([f"{PIPE}/00_fetch.sh", f"{PIPE}/config.sh"])
    log:    f"{LOG}/00_fetch.log"
    benchmark: f"{BENCH}/00_fetch.tsv"
    threads: T
    conda:  ENV
    shell:  stage("00_fetch.sh")

rule prep_reads:
    """01 - quality-encoding check, trimming, mito read recruitment (Illumina + HiFi)."""
    input:  f"{PIPE}/01_prep_reads.sh", f"{PIPE}/config.sh", REFS, f"{DONE}/00_fetch.done"
    output: done=f"{DONE}/01_reads.done",
            r1=f"{WD}/01_reads/large_mito_R1.fq.gz", r2=f"{WD}/01_reads/large_mito_R2.fq.gz"
    params: fingerprint=md5([f"{PIPE}/01_prep_reads.sh", f"{PIPE}/config.sh"] + REFS)
    log:    f"{LOG}/01_prep_reads.log"
    benchmark: f"{BENCH}/01_prep_reads.tsv"
    threads: T
    conda:  ENV
    shell:  stage("01_prep_reads.sh")

rule assemble:
    """02 - seed-independent reassemblies (GetOrganelle, NOVOPlasty, MITObim x2, MitoHiFi, hifiasm)."""
    input:  f"{PIPE}/02_assemble.sh", f"{PIPE}/config.sh", f"{DONE}/01_reads.done"
    output: done=f"{DONE}/02_assemble.done"
    params: fingerprint=md5([f"{PIPE}/02_assemble.sh", f"{PIPE}/config.sh"])
    log:    f"{LOG}/02_assemble.log"
    benchmark: f"{BENCH}/02_assemble.tsv"
    threads: T
    conda:  ENV
    shell:  stage("02_assemble.sh")

rule compare:
    """03 - common annotation, gene order, pairwise blocks, COI barcodes."""
    input:  f"{PIPE}/03_compare_assemblies.sh", f"{PIPE}/config.sh", REFS,
            py("liftover_bed", "gene_order"), f"{DONE}/02_assemble.done"
    output: done=f"{DONE}/03_compare.done",
            order=report(f"{WD}/03_compare/gene_order.tsv", category="Evidence", caption="report/gene_order.rst"),
            barcodes=f"{WD}/03_compare/bed/COI_barcodes_for_BOLD.fasta"
    params: fingerprint=md5([f"{PIPE}/03_compare_assemblies.sh", f"{PIPE}/config.sh"] + REFS + py("liftover_bed", "gene_order"))
    log:    f"{LOG}/03_compare.log"
    benchmark: f"{BENCH}/03_compare.tsv"
    threads: T
    conda:  ENV
    shell:  stage("03_compare_assemblies.sh")

rule short_reads:
    """04 - LARGE Illumina evidence: junctions, pairs/clips, GC-aware depth, indel alleles, array size, NUMTs."""
    input:  f"{PIPE}/04_short_read_evidence.sh", f"{PIPE}/config.sh", REFS,
            py("make_hypotheses", "rotate_ref", "junction_support", "depth_profile",
               "pair_evidence", "indel_allele_support", "liftover_bed"),
            f"{DONE}/03_compare.done", f"{DONE}/01_reads.done"
    output: done=f"{DONE}/04_short.done",
            alleles=report(f"{WD}/04_short/indel_alleles_LARGEreads.tsv", category="Evidence", caption="report/alleles.rst"),
            array=f"{WD}/04_short/array_size.txt",
            junctions=f"{WD}/04_short/junction_support_VGP.tsv"
    params: fingerprint=md5([f"{PIPE}/04_short_read_evidence.sh", f"{PIPE}/config.sh"] + REFS + py("make_hypotheses", "rotate_ref", "junction_support", "depth_profile", "pair_evidence", "indel_allele_support", "liftover_bed"))
    log:    f"{LOG}/04_short.log"
    benchmark: f"{BENCH}/04_short.tsv"
    threads: T
    conda:  ENV
    shell:  stage("04_short_read_evidence.sh")

rule long_reads:
    """05 - VGP HiFi per-molecule architecture (skips cleanly if no HiFi reads were fetched)."""
    input:  f"{PIPE}/05_long_read_evidence.sh", f"{PIPE}/config.sh", REFS,
            py("read_structure", "indel_allele_support", "rotate_ref", "pair_evidence", "depth_profile"),
            f"{DONE}/01_reads.done"
    output: done=f"{DONE}/05_long.done"
    params: fingerprint=md5([f"{PIPE}/05_long_read_evidence.sh", f"{PIPE}/config.sh"] + REFS + py("read_structure", "indel_allele_support", "rotate_ref", "pair_evidence", "depth_profile"))
    log:    f"{LOG}/05_long.log"
    benchmark: f"{BENCH}/05_long.tsv"
    threads: T
    conda:  ENV
    shell:  stage("05_long_read_evidence.sh")

rule graph:
    """06 - Minigraph-Cactus mitogenome pangenome; read lineage assignment and private-segment support.
    Cactus is not on conda: put the cactus-bin release (bin/ + venv) on PATH before running."""
    input:  f"{PIPE}/06_mito_graph.sh", f"{PIPE}/config.sh", REFS,
            py("graph_path_support", "liftover_bed"),
            f"{DONE}/01_reads.done", f"{DONE}/04_short.done", f"{DONE}/05_long.done"
    output: done=f"{DONE}/06_graph.done",
            gfa=f"{WD}/06_graph/sbra_mt.full.gfa",
            support=report(f"{WD}/06_graph/map/LARGE_illumina.private_segments.tsv", category="Evidence", caption="report/private_segments.rst")
    params: fingerprint=md5([f"{PIPE}/06_mito_graph.sh", f"{PIPE}/config.sh"] + REFS + py("graph_path_support", "liftover_bed"))
    log:    f"{LOG}/06_graph.log"
    benchmark: f"{BENCH}/06_graph.tsv"
    threads: T
    shell:  stage("06_mito_graph.sh", pre=(f"set +u; source {CACTUS}; set -u; " if CACTUS else ""))

# ---------------------------------------------------------------------------------------------
# 06b - the PUBLISHED mitogenome graph: same stage script, read-validated KY825190.2 instead of the
# deposited .1 (whose CR artifacts the first graph helped expose), plus extra public mitogenomes
# fetched by accession. Separate folder (06_graph_v2), so the record keeps both graphs.
#   OR168955 = S. brasiliensis assembled from SRR10079814 (Marquez et al. 2024, PLoS ONE 19:e0300830)
#   OR168945 = S. affinis (trans-Andean congener; same study)
# Edit GRAPH_V2 below (not config.sh) to change members: config.sh is an input of every stage.
V2REFS = [f"{PIPE}/refs/Sbra_UFSJ_KY825190v2.fasta", f"{PIPE}/refs/Sbra_UFSJ_KY825190v2.bed"]
GRAPH_V2 = " ".join([
    f"VGP|{PIPE}/refs/Sbra_VGP_CM059865.fasta|{PIPE}/refs/Sbra_VGP_CM059865.bed",
    f"LARGE|{PIPE}/refs/Sbra_UFSJ_KY825190v2.fasta|{PIPE}/refs/Sbra_UFSJ_KY825190v2.bed",
    f"UFMG|{PIPE}/refs/Sbra_UFMG_NC024941.fasta|{PIPE}/refs/Sbra_UFMG_NC024941.bed",
    "SbraOR168955|acc:OR168955|",
    "Saffinis|acc:OR168945|",
])
V2PRE = (f"set +u; source {CACTUS}; set -u; " if CACTUS else "") + "export GRAPH_TAG=06_graph_v2 GRAPH_GENOMES='{params.members}'; "
rule graph_v2:
    """06b - published mitogenome graph (KY825190.2 + public mitogenomes); reads re-mapped to it."""
    input:  f"{PIPE}/06_mito_graph.sh", f"{PIPE}/config.sh", REFS, V2REFS,
            py("graph_path_support", "liftover_bed"),
            f"{DONE}/06_graph.done"
    output: done=f"{DONE}/06_graph_v2.done",
            gfa=f"{WD}/06_graph_v2/sbra_mt.full.gfa",
            support=report(f"{WD}/06_graph_v2/map/LARGE_illumina.private_segments.tsv", category="Evidence", caption="report/private_segments.rst")
    params: fingerprint=md5([f"{PIPE}/06_mito_graph.sh"] + V2REFS + py("graph_path_support", "liftover_bed")), members=GRAPH_V2
    log:    f"{LOG}/06_graph_v2.log"
    benchmark: f"{BENCH}/06_graph_v2.tsv"
    threads: T
    shell:  stage("06_mito_graph.sh", pre=V2PRE)

# ---------------------------------------------------------------------------------------------
# ---- analyses after the mitogenome work; NOT part of `all` (run with: snakemake --cores 4 extras) ----
# Each rule only calls a script in extras/, so the same commands also run by hand (see extras/README.md).
EXTRAS = f"{PIPE}/extras"

rule reassembly_diffs:
    """Every LARGE re-assembly vs KY825190.1 and KY825190.2, base by base (MAFFT pairwise + difference lists)."""
    input:  f"{DONE}/02_assemble.done", f"{EXTRAS}/validation/compare_reassemblies.py"
    output: f"{WD}/07_validate/base_level/summary.tsv"
    log:    f"{WD}/logs/07_reassembly_diffs.log"
    shell:  r"""
        shopt -s nullglob; A=({WD}/02_assemblies/final/*.fasta)
        "$PYBIN" -I {EXTRAS}/validation/compare_reassemblies.py -o {WD}/07_validate/base_level \
            --ky {PIPE}/refs/Sbra_UFSJ_KY825190.fasta --v2 {PIPE}/refs/Sbra_UFSJ_KY825190v2.fasta "${{A[@]}}" > {log} 2>&1
    """

rule validate:
    """Read support of KY825190.1 and each re-assembly (circularised): low-depth runs, proper pairs, array depth."""
    input:  f"{DONE}/01_reads.done", f"{DONE}/02_assemble.done", f"{EXTRAS}/validation/validate_refs.sh"
    output: f"{WD}/07_validate/lengths.txt"
    log:    f"{WD}/logs/07_validate.log"
    shell:  "W={WD} bash {EXTRAS}/validation/validate_refs.sh > {log} 2>&1"

rule public:
    """Public-sequence analyses (Methods 2.4): lineage calls, distances, network, all sequence sets and alignments.
    Uses the GenBank files already in 08_public/ and 10_salminus_coi/ (or downloads them); needs no reads."""
    input:  REFS, f"{EXTRAS}/run_public.sh"
    output: f"{WD}/11_alignments/summary.tsv", f"{WD}/MANIFEST_public.tsv"
    log:    f"{WD}/logs/11_public.log"
    threads: 2
    shell:  "W={WD} THREADS={threads} ROSSO={ROSSO} bash {EXTRAS}/run_public.sh > {log} 2>&1"

rule graph_public:
    """Public records aligned to the mitogenome graph (vg map); lineage from the haplotype paths followed,
    compared with the linear calls (Methods 2.3-2.4). Needs graph_v2 and the public step."""
    input:  f"{DONE}/06_graph_v2.done", rules.public.output, f"{EXTRAS}/graph_public/run_graph_public.sh",
            f"{EXTRAS}/graph_public/graph_calls.py"
    output: f"{WD}/12_graph_public/graph_calls.summary.txt", f"{WD}/12_graph_public/graph_calls.tsv"
    log:    f"{WD}/logs/12_graph_public.log"
    threads: 2
    shell:  (f"set +u; source {CACTUS}; set -u; " if CACTUS else "") + "W={WD} THREADS={threads} bash {EXTRAS}/graph_public/run_graph_public.sh > {log} 2>&1"

rule fig1:
    """Fig. 1 of the manuscript: the mitogenome graph (a) and read depth over the control region (b)."""
    input:  f"{DONE}/06_graph_v2.done", rules.validate.output, f"{EXTRAS}/figures/fig1.py"
    output: f"{WD}/13_figures/Fig1.pdf", f"{WD}/13_figures/Fig1.png", f"{WD}/13_figures/Fig1.tiff"
    log:    f"{WD}/logs/13_fig1.log"
    params: pybin=PYBIN
    shell:  "W={WD} {params.pybin} {EXTRAS}/figures/fig1.py > {log} 2>&1"

rule extras:
    input:  rules.reassembly_diffs.output, rules.validate.output, rules.public.output, rules.graph_public.output, rules.fig1.output

rule versions:
    """Record the exact tool versions used (part of the methods record)."""
    output: report(f"{WD}/record/software_versions.tsv", category="Record", caption="report/versions.rst")
    log:    f"{LOG}/versions.log"
    params: pybin=PYBIN, pre=(f"source {CACTUS};" if CACTUS else "")
    shell:  r"""
    set +eu +o pipefail   # version probes may exit non-zero; never fail the workflow on them
    {params.pre}
    (
    printf "tool\tversion\n"
    for t in snakemake python3 bwa samtools minimap2 seqkit seqtk fastp bedtools mafft hifiasm \
             get_organelle_from_reads.py NOVOPlasty.pl MITObim.pl mira mitohifi.py cactus-pangenome vg prefetch efetch Rscript; do
      if command -v $t >/dev/null 2>&1; then
        case $t in
          bwa)      v=$(bwa 2>&1 | grep -m1 Version | cut -d' ' -f2);;
          samtools) v=$(samtools --version | head -1 | cut -d' ' -f2);;
          mafft)    v=$(mafft --version 2>&1 | head -1 | cut -d' ' -f1);;
          vg)       v=$(vg version 2>/dev/null | head -1 | cut -d' ' -f2-3);;
          efetch)   v=$(efetch -version 2>/dev/null | head -1);;
          python3)  v=$({params.pybin} --version 2>&1);;
          seqkit)   v=$(seqkit version 2>&1 | head -1);;
          seqtk)    v=$(seqtk 2>&1 | grep -m1 Version | cut -d' ' -f2);;
          cactus-pangenome) v=$(python3 -m pip show cactus 2>/dev/null | grep -m1 ^Version | cut -d' ' -f2);;
          NOVOPlasty.pl) v=$(grep -m1 -oiE "version[^0-9]*[0-9][0-9.]*" "$(command -v NOVOPlasty.pl)" | grep -oE "[0-9][0-9.]*");;
          MITObim.pl) v=$(MITObim.pl --version 2>&1 | grep -m1 -oE "[0-9]+\.[0-9]+(\.[0-9]+)?");;
          mira)     v=$(LC_ALL=C mira --version 2>&1 | grep -m1 -oE "[0-9]+\.[0-9]+\.[0-9]+");;
          Rscript)  v=$(Rscript -e 'cat(R.version$major, R.version$minor, sep=".")' 2>/dev/null);;
          *)        v=$($t --version 2>&1 | head -1);;
        esac
      else v="not found"; fi
      printf "%s\t%s\n" "$t" "$v"
    done
    {params.pybin} -c "import Bio, mappy; print('biopython\t'+Bio.__version__); print('mappy\t'+getattr(mappy,'__version__','?'))"
    {params.pybin} -c "
import importlib
for m in ('matplotlib', 'networkx', 'pandas'):
    try: print('python:' + m + '\t' + importlib.import_module(m).__version__)
    except Exception: print('python:' + m + '\tnot found')"
    command -v Rscript >/dev/null 2>&1 && Rscript -e 'for (p in c("ape", "igraph", "ggplot2", "ggforce", "sf", "ggrepel", "rnaturalearthdata", "ggspatial")) cat(paste0("R:", p, "\t", if (requireNamespace(p, quietly = TRUE)) as.character(packageVersion(p)) else "not found", "\n"))'
    ) > {output} 2> {log}
    """

rule rulegraph:
    """Pipeline diagram for the methods section."""
    input:  f"{PIPE}/Snakefile"
    output: report(f"{WD}/record/rulegraph.svg", category="Record", caption="report/rulegraph.rst")
    shell:  "snakemake -s {input} --rulegraph --config wd={WD} | dot -Tsvg > {output}"
