# bioseqkit demonstration workflow
#
# A minimal "data acquisition -> processing -> analysis" pipeline that drives
# the bioseqkit command-line interface. By default it runs fully offline on the
# bundled example FASTA; set `accession` in config/config.yaml (or on the
# command line with --config accession=NC_012920.1) to instead download a real
# reference from NCBI before analysing it.
#
# Usage:
#   snakemake -c1                       # run on the bundled example data
#   snakemake -c4 --config accession=NC_012920.1 k=6   # download + analyse chrM
#   snakemake -n                        # dry run (show the DAG of jobs)

configfile: "config/config.yaml"

OUTDIR = config["outdir"]


rule all:
    input:
        f"{OUTDIR}/stats.json",
        f"{OUTDIR}/kmers.tsv",
        f"{OUTDIR}/input.fa.fai",


rule fetch_input:
    """Download a reference by accession, or fall back to the local FASTA."""
    output:
        f"{OUTDIR}/input.fa",
    params:
        accession=config.get("accession", ""),
        local=config["input"],
    shell:
        r"""
        if [ -n "{params.accession}" ]; then
            python -c "from bioseqkit.entrez import efetch_fasta; \
open('{output}', 'w').write(efetch_fasta('{params.accession}'))"
        else
            cp {params.local} {output}
        fi
        """


rule stats:
    """Summary statistics as JSON."""
    input:
        f"{OUTDIR}/input.fa",
    output:
        f"{OUTDIR}/stats.json",
    shell:
        "bioseqkit stats {input} > {output}"


rule kmer:
    """Top-k canonical k-mer table."""
    input:
        f"{OUTDIR}/input.fa",
    output:
        f"{OUTDIR}/kmers.tsv",
    params:
        k=config["k"],
        top=config["top"],
        threads=config["threads"],
    threads: config["threads"]
    shell:
        "bioseqkit kmer {input} -k {params.k} --top {params.top} "
        "--canonical -t {params.threads} > {output}"


rule index:
    """Build the FAI-like random-access index next to the FASTA."""
    input:
        f"{OUTDIR}/input.fa",
    output:
        f"{OUTDIR}/input.fa.fai",
    shell:
        "bioseqkit index {input}"
