"""First-class, manifest-driven Inflection delivery packaging for HIOMRS.

Every source below is an exact named output from the current HIOMRS workflow.
The packager is prohibited from walking the results tree or selecting aliases.
"""

from snakemake.exceptions import WorkflowError


INFLECTION_DELIVERY_CFG = config["inflection_delivery"]
INFLECTION_DELIVERY_ROOT = MDIR + "deliveries/inflection"
INFLECTION_LIBRARY_MANIFEST = (
    INFLECTION_DELIVERY_ROOT
    + "/{delivery_batch}/{sample}/package_manifest.json"
)
INFLECTION_BATCH_MANIFEST_TSV = (
    INFLECTION_DELIVERY_ROOT
    + "/{delivery_batch}/inflection_delivery_manifest.tsv"
)
INFLECTION_BATCH_MANIFEST_JSON = (
    INFLECTION_DELIVERY_ROOT
    + "/{delivery_batch}/inflection_delivery_manifest.json"
)
INFLECTION_DELIVERY_LOG_ROOT = (
    INFLECTION_DELIVERY_ROOT + "/{delivery_batch}/logs"
)
INFLECTION_TIDDIT_VCF = (
    MDIR
    + "{sample}/align/"
    + HIOMRS_SR_ALIGNER
    + "/na/sv/tiddit/{sample}."
    + HIOMRS_SR_ALIGNER
    + ".tiddit.sv.sort.vcf.gz"
)
INFLECTION_SMN12_SUMMARY = (
    MDIR
    + "{sample}/align/"
    + HIOMRS_SR_ALIGNER
    + "/na/htd/smn12/{sample}."
    + HIOMRS_SR_ALIGNER
    + ".na.smn12.summary.json"
)


def _inflection_required_batch(wildcards):
    if not HIOMRS_EMIT_TERMINAL_VCF:
        raise WorkflowError(
            "Inflection delivery requires hiomrs.emit_terminal_vcf: true; "
            "the package will not silently omit or derive another SNV callset."
        )
    configured = str(config.get("inflection_delivery_batch_id") or "")
    if not configured:
        raise WorkflowError(
            "inflection_delivery_batch_id is required to build an Inflection delivery."
        )
    if SAFE_WORKFLOW_IDENTIFIER_RE.fullmatch(configured) is None:
        raise WorkflowError(
            "inflection_delivery_batch_id must contain only ASCII letters, digits, "
            "underscore, dot, and hyphen; DayOA will not rewrite it."
        )
    if str(wildcards.delivery_batch) != configured:
        raise WorkflowError(
            "Inflection delivery target batch does not match configured "
            f"inflection_delivery_batch_id: target={wildcards.delivery_batch!s}; "
            f"configured={configured}"
        )
    if tuple(HIOMRS_SPECIALTY_GENES) != tuple(HIOMRS_SPECIALTY_PINNED_GENES):
        raise WorkflowError(
            "Inflection delivery requires the exact configured 14-gene SegDup "
            "panel: " + ",".join(HIOMRS_SPECIALTY_PINNED_GENES)
        )
    return configured


def _inflection_library_row(wildcards):
    matches = samples[samples["analysis_unit_uid"] == wildcards.sample]
    if len(matches.index) != 1:
        raise WorkflowError(
            f"Inflection delivery requires exactly one resolved analysis-unit row for "
            f"ANALYSIS_UNIT_UID={wildcards.sample!s}; observed {len(matches.index)}."
        )
    row = matches.iloc[0]
    required = ("SPECIMEN_ID", "SAMPLEID")
    optional = (
        "SPECIMEN_EUID",
        "SAMPLE_EUID",
        "LIBRARY_EUID",
        "DELIVERY_EUID",
        "DELIVERY_PROFILE",
        "CUSTOMER_DELIVERY_ID",
    )
    values = {}
    for field in required:
        value = str(row.get(field, "") or "")
        if value.strip().lower() in {"", "na", "none", "null", "nan"}:
            raise WorkflowError(
                f"{field} is required for Inflection delivery analysis unit "
                f"{wildcards.sample!s}; DayOA will not infer it."
            )
        if SAFE_WORKFLOW_IDENTIFIER_RE.fullmatch(value) is None:
            raise WorkflowError(
                f"Unsafe {field}={value!r} for Inflection delivery analysis unit "
                f"{wildcards.sample!s}; DayOA will not rewrite it."
            )
        values[field] = value
    for field in optional:
        value = str(row.get(field, "") or "")
        if value.strip().lower() in {"na", "none", "null", "nan"}:
            value = ""
        if value and SAFE_WORKFLOW_IDENTIFIER_RE.fullmatch(value) is None:
            raise WorkflowError(
                f"Unsafe {field}={value!r} for Inflection analytical package "
                f"{wildcards.sample!s}; DayOA will not rewrite it."
            )
        values[field] = value
    return values


def _inflection_row_value(field):
    return lambda wildcards: _inflection_library_row(wildcards)[field]


def _inflection_package_manifests(wildcards):
    _inflection_required_batch(wildcards)
    return expand(
        INFLECTION_LIBRARY_MANIFEST,
        delivery_batch=wildcards.delivery_batch,
        sample=sorted(SSAMPS),
    )


rule build_inflection_expected_artifacts:
    """Declare exact post-call artifacts for one Inflection analysis package."""
    input:
        snv_vcf=HIOMRS_FINAL_HARDCALLS,
        cnv_vcf=HIOMRS_FINAL_CNV,
        hiomrs_sv_callsets=rules.hiomrs_longreadsv.output.callsets,
        hiomrs_sv_selector=rules.hiomrs_longreadsv.output.selector,
        tiddit_sv_vcf=INFLECTION_TIDDIT_VCF,
        mito_vcf=HIOMRS_FINAL_MITO_VCF,
        expansionhunter_vcf=HIOMRS_FINAL_EH_VCF,
        segdup_merged_vcf=HIOMRS_FINAL_SEGDUP_MERGED,
        smn12_summary=INFLECTION_SMN12_SUMMARY,
        sr_cram=HIOMRS_FINAL_SR_CRAM,
    output:
        tsv=MDIR
        + "deliveries/inflection/_expected/{delivery_batch}/{sample}/expected_artifacts.tsv",
        json=MDIR
        + "deliveries/inflection/_expected/{delivery_batch}/{sample}/expected_artifacts.json",
    params:
        cluster_sample=ret_sample,
        delivery_batch=_inflection_required_batch,
    log:
        MDIR
        + "deliveries/inflection/{delivery_batch}/logs/{sample}.expected_artifacts.log",
    benchmark:
        MDIR
        + "{sample}/benchmarks/{sample}.inflection.{delivery_batch}.expected_artifacts.bench.tsv",
    threads: 1
    conda:
        INFLECTION_DELIVERY_CFG["env_yaml"]
    resources:
        threads=1,
        vcpu=1,
        mem_mb=INFLECTION_DELIVERY_CFG["mem_mb"],
        time=INFLECTION_DELIVERY_CFG["time"],
        partition=INFLECTION_DELIVERY_CFG["partition"],
    shell:
        r"""
        set -euo pipefail
        mkdir -p "$(dirname {log:q})" "$(dirname {output.tsv:q})"
        : > {log:q}
        bin/dayoa_expected_artifacts.py build \
          --analysis-unit-uid {wildcards.sample:q} \
          --sv-selector {input.hiomrs_sv_selector:q} \
          --sv-callsets-dir {input.hiomrs_sv_callsets:q} \
          --snv-vcf {input.snv_vcf:q} \
          --cnv-vcf {input.cnv_vcf:q} \
          --tiddit-sv-vcf {input.tiddit_sv_vcf:q} \
          --mitochondrial-vcf {input.mito_vcf:q} \
          --expansionhunter-vcf {input.expansionhunter_vcf:q} \
          --segdup-merged-vcf {input.segdup_merged_vcf:q} \
          --smn12-summary {input.smn12_summary:q} \
          --short-read-cram {input.sr_cram:q} \
          --output-tsv {output.tsv:q} \
          --output-json {output.json:q} \
          >> {log:q} 2>&1
        test -s {output.tsv:q}
        test -s {output.json:q}
        """


rule package_inflection_library:
    """Materialize one validated, transactional Inflection library package."""
    input:
        snv_vcf=HIOMRS_FINAL_HARDCALLS,
        snv_index=HIOMRS_FINAL_HARDCALLS + ".tbi",
        cnv_vcf=HIOMRS_FINAL_CNV,
        cnv_index=HIOMRS_FINAL_CNV + ".tbi",
        hiomrs_sv_callsets=rules.hiomrs_longreadsv.output.callsets,
        hiomrs_sv_selector=rules.hiomrs_longreadsv.output.selector,
        expected_artifacts_tsv=rules.build_inflection_expected_artifacts.output.tsv,
        expected_artifacts_json=rules.build_inflection_expected_artifacts.output.json,
        tiddit_sv_vcf=INFLECTION_TIDDIT_VCF,
        tiddit_sv_index=INFLECTION_TIDDIT_VCF + ".tbi",
        mito_vcf=HIOMRS_FINAL_MITO_VCF,
        mito_index=HIOMRS_FINAL_MITO_TBI,
        expansionhunter_vcf=HIOMRS_FINAL_EH_VCF,
        expansionhunter_json=HIOMRS_FINAL_EH_JSON,
        expansionhunter_report=HIOMRS_FINAL_EH_REPORT,
        segdup_summary=HIOMRS_FINAL_SEGDUP_YAML,
        segdup_gene_vcfs=HIOMRS_FINAL_SEGDUP_GENE_VCFS,
        segdup_gene_indexes=HIOMRS_FINAL_SEGDUP_GENE_TBIS,
        segdup_merged_vcf=HIOMRS_FINAL_SEGDUP_MERGED,
        segdup_merged_index=HIOMRS_FINAL_SEGDUP_MERGED + ".tbi",
        smn12_summary=INFLECTION_SMN12_SUMMARY,
        sr_cram=HIOMRS_FINAL_SR_CRAM,
        sr_crai=HIOMRS_FINAL_SR_CRAM + ".crai",
        reference=lambda wildcards: _hiomrs_config_path("reference_fasta"),
        reference_fai=lambda wildcards: _hiomrs_config_path("reference_fasta") + ".fai",
    output:
        # Keep wildcards literal here and in log/benchmark.  The repository-wide
        # static contract intentionally does not expand named path constants.
        manifest=MDIR
        + "deliveries/inflection/{delivery_batch}/{sample}/package_manifest.json",
    params:
        cluster_sample=ret_sample,
        delivery_batch=_inflection_required_batch,
        delivery_profile=_inflection_row_value("DELIVERY_PROFILE"),
        delivery_euid=_inflection_row_value("DELIVERY_EUID"),
        customer_delivery_id=_inflection_row_value("CUSTOMER_DELIVERY_ID"),
        sample_id=_inflection_row_value("SAMPLEID"),
        specimen_id=_inflection_row_value("SPECIMEN_ID"),
        specimen_euid=_inflection_row_value("SPECIMEN_EUID"),
        sample_euid=_inflection_row_value("SAMPLE_EUID"),
        library_euid=_inflection_row_value("LIBRARY_EUID"),
        expansionhunter_source_sample_id=lambda wildcards: (
            f"{wildcards.sample}.hiomrs_sr.na"
        ),
        analysis_root=HIOMRS_ANALYSIS_ROOT,
    log:
        MDIR
        + "deliveries/inflection/{delivery_batch}/logs/{sample}.package.log",
    benchmark:
        MDIR
        + "{sample}/benchmarks/{sample}.inflection.{delivery_batch}.package.bench.tsv",
    threads: INFLECTION_DELIVERY_CFG["threads"]
    conda:
        INFLECTION_DELIVERY_CFG["env_yaml"]
    resources:
        threads=INFLECTION_DELIVERY_CFG["threads"],
        vcpu=INFLECTION_DELIVERY_CFG["threads"],
        mem_mb=INFLECTION_DELIVERY_CFG["mem_mb"],
        time=INFLECTION_DELIVERY_CFG["time"],
        partition=INFLECTION_DELIVERY_CFG["partition"],
    shell:
        r"""
        set -euo pipefail
        mkdir -p "$(dirname {log:q})"
        : > {log:q}
