# The main entry point of your workflow.

include: "rules/common.smk"

def get_ds_bams(P,B):
    d = {}
    for b in B:
        fl = OUT_DIR+"sWGS_fitting/"+P+"_"+str(b)+"kb/absolute_PRE_down_sampling/"+P+"_fit_QC_predownsample.tsv"
        if os.path.isfile(fl):
            f = pd.read_table(fl).set_index(["SAMPLE_ID"], drop=False)
            if not f.empty:
                if f["use"].dtype == bool and all(~f.use.isnull()):
                    ftb = f[(f['use'] == True)]
                    if all(~ftb.SAMPLE_ID.duplicated()):
                        d[str(b)] = list(ftb['SAMPLE_ID'])
                    else:
                        sys.exit("QC file contains duplicated sample ids marked 'TRUE'")
                else:
                    sys.exit("QC file 'use' column contains non-boolean values")
            else:
                sys.exit("QC file is empty. Filtering criteria may need adjusting")
        else:
            sys.exit("QC file from stage 1 is missing")
    return(d)

# Set new sample list based on filtered QC from stage 1
PROJECT=config["project_name"]
BIN=config["bins"]

if any(samplesheet.SAMPLE_ID.duplicated()):
    sys.exit("Sample sheet contains duplicated sample ids")


prplpu = "FALSE"
if all(samplesheet.precPloidy.notna()) and all(samplesheet.precPurity.notna()):
    prplpu = "TRUE"

SAMPLE_LISTS=get_ds_bams(PROJECT,BIN)

rule all:
    input:
        expand(OUT_DIR+"sWGS_fitting/{project}_{bin}kb/absolute_POST_down_sampling/abs_cn_rds/{project}_{bin}kb_ds_absCopyNumber.rds",project=config["project_name"],bin=config["bins"]),
        expand(OUT_DIR+"sWGS_fitting/{project}_{bin}kb/absolute_POST_down_sampling/abs_cn_rds/{project}_{bin}kb_ds_abs_fits.tsv",project=config["project_name"],bin=config["bins"])

# pipeline rules
include: "rules/ds_symlink.smk"
include: "rules/downsample.smk"
include: "rules/downsampled_rel_rds.smk"
include: "rules/rel_to_abs.smk"
