"""Manifest-only Inflection customer report and transactional delivery set."""

from snakemake.exceptions import WorkflowError


INFLECTION_REPORT_ROOT = (
    INFLECTION_DELIVERY_ROOT + "/{delivery_batch}/reports"
)
INFLECTION_REPORT_STAGE = (
    INFLECTION_REPORT_ROOT + "/multiqc_inputs/inflection"
)
INFLECTION_FINAL_HTML = INFLECTION_REPORT_ROOT + "/INFLECTION_final_multiqc.html"
INFLECTION_FINAL_ORIGINAL_HTML = (
    INFLECTION_REPORT_ROOT + "/INFLECTION_final_multiqc.original.html"
)
INFLECTION_FINAL_DATA_JSON = (
    INFLECTION_REPORT_ROOT
    + "/INFLECTION_final_multiqc_data/multiqc_data.json"
)
INFLECTION_FINAL_DATA_ZIP = (
    INFLECTION_REPORT_ROOT + "/INFLECTION_final_multiqc_data.zip"
)
INFLECTION_EVIDENCE_MANIFEST = (
    INFLECTION_REPORT_ROOT + "/inflection_evidence_manifest.json"
)
INFLECTION_ARTIFACT_QC_MD = (
    INFLECTION_REPORT_ROOT + "/inflection_artifact_qc.md"
)
INFLECTION_ARTIFACT_QC_TSV = (
    INFLECTION_REPORT_ROOT + "/inflection_artifact_qc.tsv"
)
INFLECTION_ARTIFACT_QC_JSON = (
    INFLECTION_REPORT_ROOT + "/inflection_artifact_qc.json"
)
INFLECTION_DELIVERY_SET_MANIFEST = (
    INFLECTION_DELIVERY_ROOT
    + "/{delivery_batch}/INFLECTION_delivery_set/delivery_set_manifest.json"
)
INFLECTION_STAGE_LOG = (
    INFLECTION_DELIVERY_ROOT + "/{delivery_batch}/logs/inflection_multiqc_stage.log"
)
INFLECTION_STAGE_BENCHMARK = (
    MDIR + "benchmarks/inflection_delivery.{delivery_batch}.multiqc_stage.bench.tsv"
)
INFLECTION_FINAL_LOG = (
    INFLECTION_DELIVERY_ROOT + "/{delivery_batch}/logs/inflection_multiqc_final.log"
)
INFLECTION_FINAL_BENCHMARK = (
    MDIR + "benchmarks/inflection_delivery.{delivery_batch}.multiqc_final.bench.tsv"
)
INFLECTION_SET_LOG = (
    INFLECTION_DELIVERY_ROOT + "/{delivery_batch}/logs/inflection_delivery_set.log"
)
INFLECTION_SET_BENCHMARK = (
    MDIR + "benchmarks/inflection_delivery.{delivery_batch}.delivery_set.bench.tsv"
)
INFLECTION_ARTIFACT_QC_LOG = (
    INFLECTION_DELIVERY_ROOT + "/{delivery_batch}/logs/inflection_artifact_qc.log"
)
INFLECTION_ARTIFACT_QC_BENCHMARK = (
    MDIR + "benchmarks/inflection_delivery.{delivery_batch}.artifact_qc.bench.tsv"
)


def _inflection_artifact_qc_target_files(wildcards):
    configured = str(config.get("inflection_delivery_batch_id") or "")
    if not configured:
        raise WorkflowError(
            "inflection_delivery_batch_id is required to request the independent "
            "Inflection artifact QC report."
        )
    if SAFE_WORKFLOW_IDENTIFIER_RE.fullmatch(configured) is None:
        raise WorkflowError(
            "inflection_delivery_batch_id contains unsafe characters; DayOA will "
            "not rewrite it."
        )
    return [
        path.format(delivery_batch=configured)
        for path in (
            INFLECTION_ARTIFACT_QC_MD,
            INFLECTION_ARTIFACT_QC_TSV,
            INFLECTION_ARTIFACT_QC_JSON,
        )
    ]


localrules: produce_inflection_artifact_qc_report


rule produce_inflection_artifact_qc_report:
    """Independently request the configured batch's Markdown/JSON/TSV audit."""
    input:
        _inflection_artifact_qc_target_files
    params:
        cluster_sample="produce_inflection_artifact_qc_report",
    log:
        MDIR + "logs/produce_inflection_artifact_qc_report.log",
    benchmark:
        MDIR + "benchmarks/produce_inflection_artifact_qc_report.bench.tsv",
    threads: 1
    shell:
        r"""
        set -euo pipefail
        mkdir -p "$(dirname {log:q})"
        printf '%s\n' 'Inflection artifact QC report complete.' > {log:q}
        """


rule create_inflection_artifact_qc_report:
    """Audit exact batch/package declarations without filesystem discovery."""
    input:
        batch_json=INFLECTION_BATCH_MANIFEST_JSON,
        batch_tsv=INFLECTION_BATCH_MANIFEST_TSV,
    output:
        md=INFLECTION_ARTIFACT_QC_MD,
        tsv=INFLECTION_ARTIFACT_QC_TSV,
        json=INFLECTION_ARTIFACT_QC_JSON,
    params:
        delivery_batch=_inflection_required_batch,
        cluster_sample="inflection_artifact_qc",
    log:
        INFLECTION_ARTIFACT_QC_LOG,
    benchmark:
        INFLECTION_ARTIFACT_QC_BENCHMARK,
    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 {output.md:q})" "$(dirname {log:q})"
        : > {log:q}
        bin/dayoa_inflection_artifact_qc.py \
          --batch-json {input.batch_json:q} \
          --batch-tsv {input.batch_tsv:q} \
          --output-md {output.md:q} \
          --output-tsv {output.tsv:q} \
          --output-json {output.json:q} \
          >> {log:q} 2>&1
        test -s {output.md:q}
        test -s {output.tsv:q}
        test -s {output.json:q}
        """


rule stage_inflection_multiqc:
    """Stage only deterministic evidence named by the validated batch manifest."""
    input:
        batch_json=INFLECTION_BATCH_MANIFEST_JSON,
        batch_tsv=INFLECTION_BATCH_MANIFEST_TSV,
    output:
        done=INFLECTION_REPORT_STAGE + "/.stage.done",
        manifest=INFLECTION_REPORT_STAGE + "/inflection_multiqc_stage_manifest.json",
        selectors=INFLECTION_REPORT_STAGE + "/dayoa_report_selectors.json",
        lsmc_config=INFLECTION_REPORT_STAGE + "/multiqc_inflection_lsmc.yaml",
        original_config=INFLECTION_REPORT_STAGE + "/multiqc_inflection_original.yaml",
    params:
        delivery_batch=_inflection_required_batch,
        stage_dir=INFLECTION_REPORT_STAGE,
        cluster_sample="inflection_multiqc_stage",
    log:
        INFLECTION_STAGE_LOG,
    benchmark:
        INFLECTION_STAGE_BENCHMARK,
    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})"
        : > {log:q}
        bin/dayoa_inflection_report.py stage \
          --batch-json {input.batch_json:q} \
          --batch-tsv {input.batch_tsv:q} \
          --stage-dir {params.stage_dir:q} \
          >> {log:q} 2>&1
        test -s {output.done:q}
        test -s {output.manifest:q}
        test -s {output.selectors:q}
        test -s {output.lsmc_config:q}
        test -s {output.original_config:q}
        """


rule create_inflection_multiqc_final:
    """Create independent branded and original customer reports without OpenAI."""
    input:
        batch_json=INFLECTION_BATCH_MANIFEST_JSON,
        batch_tsv=INFLECTION_BATCH_MANIFEST_TSV,
        stage_done=rules.stage_inflection_multiqc.output.done,
        stage_manifest=rules.stage_inflection_multiqc.output.manifest,
        selectors=rules.stage_inflection_multiqc.output.selectors,
        lsmc_config=rules.stage_inflection_multiqc.output.lsmc_config,
        original_config=rules.stage_inflection_multiqc.output.original_config,
    output:
        html=INFLECTION_FINAL_HTML,
        original_html=INFLECTION_FINAL_ORIGINAL_HTML,
        data_json=INFLECTION_FINAL_DATA_JSON,
        data_zip=INFLECTION_FINAL_DATA_ZIP,
        evidence=INFLECTION_EVIDENCE_MANIFEST,
    params:
        delivery_batch=_inflection_required_batch,
        stage_dir=INFLECTION_REPORT_STAGE,
        report_root=INFLECTION_REPORT_ROOT,
        data_dir=INFLECTION_REPORT_ROOT + "/INFLECTION_final_multiqc_data",
        cluster_sample="inflection_multiqc_final",
    log:
        INFLECTION_FINAL_LOG,
    benchmark:
        INFLECTION_FINAL_BENCHMARK,
    threads: config["multiqc"]["threads"]
    conda:
        "../envs/multiqc_v0.1.yaml"
    resources:
        threads=config["multiqc"]["threads"],
        vcpu=config["multiqc"]["threads"],
        partition=config["multiqc"]["partition"],
    shell:
        r"""
        set -euo pipefail
        mkdir -p {params.report_root:q} "$(dirname {log:q})"
        : > {log:q}
        unset OPENAI_API_KEY OPENAI_TOKEN DAYOA_OPENAI_TOKEN || true
        stage_dir="$(cd {params.stage_dir:q} && pwd -P)"
        report_root="$(cd {params.report_root:q} && pwd -P)"
        (
          cd "$stage_dir"
          multiqc . \
            -c multiqc_inflection_lsmc.yaml \
            -o "$report_root" \
            -n INFLECTION_final_multiqc.html \
            -m custom_content \
            --strict -f
          multiqc . \
            -c multiqc_inflection_original.yaml \
            -o "$report_root" \
            -n INFLECTION_final_multiqc.original.html \
            -m custom_content \
            --strict -f --no-data-dir
        ) >> {log:q} 2>&1
        test -s {output.html:q}
        test -s {output.original_html:q}
        test -s {output.data_json:q}
        bin/dayoa_inflection_report.py archive-data \
          --data-dir {params.data_dir:q} \
          --output {output.data_zip:q} \
          >> {log:q} 2>&1
