# --- new: point the workflow report to your main RST file
report: "index.rst"

from snakebids import bids, generate_inputs
from pathlib import Path

def path_placeholderstring():
	# "{datadir}/{device}/{device}-{session}/{filename}"
	return "{sub}/{session}/{modality}/{sub}-{session}-{task}"

def generate_input_path(ext):
	return path_placeholderstring() + ext

def generate_pipe_path(step_name, ext):
	return str(Path('preproc-results') / step_name / path_placeholderstring()) + ext

rule lowpass:
    """Applies a lowpass filter to the input ECoG signal."""
    params: 
        cutoff=config['prep']['cutoff_lp'],   # Cutoff frequency in Hz
        order=config['prep']['order'],        # Order of the filter
        btype='lowpass'
    input:
        raw=ancient(generate_pipe_path("denoised", ".zarr"))
    output:
        filtered=report(
            directory(generate_pipe_path("lowpass", ".zarr")),
            caption=(
                "Lowpass-filtered ECoG signal generated by **01_lowpass.py**. "
                "Filter parameters: cutoff={params.cutoff} Hz, order={params.order}. "
                "Removes high-frequency noise while preserving local field potential structure."
            ),
            category="Preprocessing",
            subcategory="Filtering",
            labels=["ecog","filter","lowpass"]
        )
    script:
        "scripts/01_filter.py"

rule feature:
    """Extracts statistical and spectral features from ECoG channels."""
    params:
        window_size=config['bad']['window_size'],
        window_step=config['bad']['window_step'],
        zscore=True
    input:
        lowpass=generate_pipe_path("downsample", ".zarr")
    output:
        feature=report(
            directory(generate_pipe_path("feature", ".zarr")),
            caption=(
                "Extracted feature dataset produced by **02_feature.py**. "
                "Features computed over sliding windows "
                "(size={params.window_size}, step={params.window_step}) and z-scored per channel. "
                "Used as input for bad-channel detection."
            ),
            category="Feature Extraction",
            subcategory="Statistical Features",
            labels=["feature","windowed","zarr"]
        )
    script:
        "scripts/02_feature.py"

rule badlabel:
    """Identifies bad ECoG channels via unsupervised outlier detection."""
    input:
        feature=generate_pipe_path("feature", ".zarr")
    output:
        badlabel=report(
            generate_pipe_path("badlabel", ".npy"),
            caption=(
                "Channel-level bad-label array generated by **03_badlabel.py**. "
                "Each element indicates a detected outlier channel (1 = bad, 0 = good), "
                "derived from statistical features via KNN-based unsupervised detection (k={params.knn})."
            ),
            category="Quality Control",
            subcategory="Outlier Detection",
            labels=["labels","qc","knn"]
        )
    params:
        knn=config['bad']['knn']
    script:
        "scripts/03_badlabel.py"

rule interpolate:
    """Interpolates bad channels to reconstruct a continuous ECoG signal."""
    input:
        raw=generate_pipe_path("raw_zarr", ".zarr"),
        badlabel=generate_pipe_path("badlabel", ".npy")
    output:
        interp=report(
            directory(generate_pipe_path("interpolate", ".zarr")),
            caption=(
                "Interpolated ECoG dataset produced by **04_interpolate.py**. "
                "Bad channels identified in the previous step are replaced by temporally "
                "and spatially interpolated signals to maintain continuity."
            ),
            category="Postprocessing",
            subcategory="Interpolation",
            labels=["interpolate","reconstruction","zarr"]
        )
    script:
        "scripts/04_interpolate.py"
