"""Integration tests for executing CWL workflows used in qualpipe."""

import subprocess
from enum import Enum
from pathlib import Path

import pytest


class WorkflowGroup(Enum):
    """Enumeration of workflow groups used to locate CWL files."""

    METRIC = "metric"
    # Add other groups as needed


def run_cwl(workflow, config=None):
    """Run a CWL workflow and return the stderr output from cwltool."""
    command = ["cwltool", workflow]
    if config is not None:
        command.append(config)
    try:
        result = subprocess.run(command, check=True, capture_output=True, text=True)
        return result.stderr
    except subprocess.CalledProcessError as e:
        return e.stderr


# Common base path for all configuration files
DEFAULT_CONFIG_BASE_PATH = Path(__file__).parent / "../docs/static/examples"

# Define your test cases declaratively
# Test case parameters: (group, id, base_path, config_kwargs)
# - group: WorkflowGroup enum (METRIC or others)
# - id: Use case identifier string (e.g., "1.2.1")
# - base_path: Path to user_guide directory (fixtures will add their specific subdirectories)
# - config_kwargs: Dictionary of configuration overrides
USECASE_PARAMS = [
    (
        WorkflowGroup.METRIC,
        "1.2.1",
        DEFAULT_CONFIG_BASE_PATH,
        {
            "dl1_monitoring_data": {"class": "File", "path": "DL1_MON_FILE_1"},
        },
    ),
    (
        WorkflowGroup.METRIC,
        "1.2.1",
        DEFAULT_CONFIG_BASE_PATH,
        {
            "dl1_monitoring_data": {"class": "File", "path": "DL1_MON_FILE_2"},
        },
    ),
]


@pytest.mark.integration()
@pytest.mark.parametrize(
    ("group", "id", "base_path", "config_kwargs"),
    [
        pytest.param(
            g, i, base_path, kwargs, marks=pytest.mark.verifies_usecase(f"UC-140-{i}")
        )
        for g, i, base_path, kwargs in USECASE_PARAMS
    ],
)
def test_run_cwl(group, id, base_path, config_kwargs, workflow_config):
    """Run the selected workflow and assert that cwltool reaches a final state."""
    path_to_workflows = Path(__file__).parent / "../workflows"

    # Use glob to find the workflow file
    workflow_pattern = f"uc-140-{id}*.cwl"
    workflow_file_path = path_to_workflows / group.value

    try:
        workflow_file = next(workflow_file_path.glob(workflow_pattern))
    except StopIteration:
        pytest.fail(
            f"No matching workflow file found for pattern {workflow_pattern} "
            f"in {workflow_file_path}."
        )

    # Use the populated config from the fixture
    output = run_cwl(workflow_file, workflow_config)
    assert (
        "Final process status is success" in output
        or "Final process status is temporaryFail" in output
    )
    if "Final process status is temporaryFail" in output:
        assert "exited with status: 100" in output
