import os
import sys
import shutil
from datetime import datetime
import glob
from snakemake.utils import min_version
import seqnado.utils_chipseq as chip_utils
import seqnado.utils as utils
import pandas as pd

start_time = datetime.now()
ASSAY = "ChIP"


configfile: "config_chip.yml"


container: "library://asmith151/ngs-pipeline/ngs:latest"

utils.format_config_dict(config)
pipeline_tools = utils.get_pipeline_tools(config, assay=ASSAY)

# Methods to use
PILEUP_METHODS = [
    method for method in ["deeptools", "homer"] if pipeline_tools[method] == True
]
PEAK_CALL_METHODS = [
    method
    for method in ["macs", "lanceotron", "homer"]
    if pipeline_tools[method] == True
]

# Convinience function that needs to be corrected
# utils.set_up_chromsizes(config)

# Get dataframe of samples
if os.path.exists(config["design"]):
    # Expect columns - sample fq1 fq2 antibody control
    CHIP_SAMPLES = chip_utils.ChipseqFastqSamples(
        pd.read_csv(config["design"], sep="[\s+,\t]", engine="python")
    )

else:
    # Use pattern matching to get samples
    fq_files = list(utils.get_fastq_files("."))
    if fq_files:
        CHIP_SAMPLES = chip_utils.ChipseqFastqSamples.from_files(fq_files)
    else:
        raise ValueError("No FASTQ files found in the working directory")


CHIP_SAMPLES.symlink_fastq_files(outdir="fastq")


DESIGN = CHIP_SAMPLES.design
ANTIBODIES = CHIP_SAMPLES.antibodies
FASTQ_FILES = CHIP_SAMPLES.fastq_files
SAMPLE_NAMES = CHIP_SAMPLES.sample_names_all
SAMPLE_NAMES_IP = CHIP_SAMPLES.sample_names_ip
SAMPLE_NAMES_CONTROL = CHIP_SAMPLES.sample_names_control
SAMPLE_NAMES_PAIRED = CHIP_SAMPLES.paired_ip_and_control

include: "rules/qc.smk"
include: "rules/fastq_trim.smk"
include: "rules/align.smk"
include: "rules/alignment_post_processing.smk"
include: "rules/peak_call.smk"
include: "rules/pileup.smk"
include: "rules/hub.smk"


rule all:
    input:
        mutiqc_full="qc/full_qc_report.html",
        pileups=expand(
            "bigwigs/{method}/{sample}.bigWig",
            sample=SAMPLE_NAMES,
            method=PILEUP_METHODS,
        ),
        peaks=expand(
            "peaks/{method}/{ip}.bed",
        ip=[
        f"{row.sample}_{row.antibody}"
                for row in CHIP_SAMPLES.design.itertuples()
            ],
            method=PEAK_CALL_METHODS,
        ),
        hub=os.path.join(
            config["ucsc_hub_details"]["directory"],
            f"{config['ucsc_hub_details']['name']}.hub.txt",
        ),


onsuccess:
    slurm_files = glob.glob("slurm-*.out")
    sps_files = glob.glob("sps-*")

    for fn in [*slurm_files, *sps_files]:
        try:
            if not os.path.isdir(fn):
                os.remove(fn)
            else:
                shutil.rmtree(fn)

        except Exception as e:
            print(e)

onerror:
    log_out = "seqnado_error.log"
    shutil.copyfile(log, log_out)
    print(
        f"An error occurred. Please check the log file {log_out} for more information."
    )
