"""
Snakemake workflow for Health Economic Analysis Pipeline.

This workflow manages the execution of the DCEA analysis using the vop-poc-nz package.
It supports versioning via an output directory parameter.

Usage:
    snakemake -c1                              # Run with 1 core
    snakemake -c1 --config version=v1.0        # Run with version tag
    snakemake -c1 -n                           # Dry run (preview)
    snakemake -c4                              # Run with 4 cores (parallel)
    snakemake --dag | dot -Tpng > dag.png      # Visualize workflow

Prerequisites:
    pip install vop-poc-nz snakemake
"""

# Load parameters from local file (generated by vop-poc-nz init)
configfile: "parameters.yaml"

# Configuration
VERSION = config.get("version", "latest")
OUTPUT_DIR = f"output/{VERSION}"

# Default target: run full pipeline
rule all:
    input:
        f"{OUTPUT_DIR}/reports/policy_brief.md",
        f"{OUTPUT_DIR}/combined_report.md",
        f"{OUTPUT_DIR}/figures/dashboard_ce_voi_societal.png",
        f"{OUTPUT_DIR}/figures/discordance_loss.png"

# Run the full analysis pipeline
rule run_analysis:
    output:
        directory(f"{OUTPUT_DIR}/figures"),
        directory(f"{OUTPUT_DIR}/reports"),
        f"{OUTPUT_DIR}/reports/policy_brief.md",
        f"{OUTPUT_DIR}/combined_report.md",
        f"{OUTPUT_DIR}/figures/dashboard_ce_voi_societal.png",
        f"{OUTPUT_DIR}/figures/discordance_loss.png"
    params:
        output_dir = OUTPUT_DIR
    log:
        f"{OUTPUT_DIR}/logs/analysis.log"
    shell:
        "vop-poc-nz run --output-dir {params.output_dir} 2>&1 | tee {log}"

# Run analysis only (skip reporting)
rule analysis_only:
    output:
        f"{OUTPUT_DIR}/results.pkl"
    params:
        output_dir = OUTPUT_DIR
    log:
        f"{OUTPUT_DIR}/logs/analysis_only.log"
    shell:
        "vop-poc-nz run --output-dir {params.output_dir} --skip-reporting 2>&1 | tee {log}"

# Generate reports from existing results
rule reports_only:
    input:
        f"{OUTPUT_DIR}/results.pkl"
    output:
        f"{OUTPUT_DIR}/reports/policy_brief.md"
    params:
        output_dir = OUTPUT_DIR
    log:
        f"{OUTPUT_DIR}/logs/reports.log"
    shell:
        "vop-poc-nz report --results-file {input} --output-dir {params.output_dir} 2>&1 | tee {log}"

# Clean outputs for current version
rule clean:
    shell:
        "rm -rf {OUTPUT_DIR}"

# Clean all outputs
rule clean_all:
    shell:
        "rm -rf output/"

# Quality checks
rule lint:
    shell:
        "ruff check ."

rule format:
    shell:
        "ruff format ."

rule test:
    shell:
        "pytest -v --cov=. --cov-report=xml"
