from behave.runner import Runner
from behave.configuration import Configuration
from pathlib import Path


def test_runner(*data) -> Path:
    """Execute tests in a parallel worker process.
    
    Args:
        data: Tuple of (parallel_index, args, args_unknown, tests)
            - parallel_index: Worker index for this process
            - args: Configuration namespace with output, D (definitions), tags
            - args_unknown: Additional arguments to pass to Behave
            - tests: List of test file paths to execute
    
    Returns:
        Path to generated JSON results file
    """
    parallel_index, args, args_unknown, tests = data
    json_result_dir: Path = args.output.joinpath('json_results')
    output_file: Path = json_result_dir.joinpath(f'{parallel_index}.json')

    json_result_dir.mkdir(parents=True, exist_ok=True)

    config = _build_configuration(args, parallel_index, output_file, tests, args_unknown)
    Runner(config).run()
    return output_file


def _build_configuration(args, parallel_index: int, output_file: Path, tests: list, args_unknown: list) -> Configuration:
    """Build Behave Configuration object from structured parameters.
    
    This avoids hardcoding command-line argument strings by centralizing
    configuration logic into semantic helper functions.
    """
    command_args = []
    _add_user_definitions(command_args, args.D, parallel_index)
    _add_output_config(command_args, output_file)
    _add_tags_config(command_args, args.tags)
    command_args.append('--no-summary')
    command_args.extend(args_unknown)
    command_args.extend(tests)
    return Configuration(command_args=command_args)


def _add_user_definitions(command_args: list, user_defs, parallel_index: int) -> None:
    """Add user-defined variables and parallel index to configuration."""
    for key, value in vars(user_defs).items():
        command_args.extend(['-D', f'{key}={value}'])
    command_args.extend(['-D', f'parallel={parallel_index}'])


def _add_output_config(command_args: list, output_file: Path) -> None:
    """Configure JSON output formatter with target file path."""
    command_args.extend(['-f', 'json', '-o', str(output_file)])


def _add_tags_config(command_args: list, tags: list) -> None:
    """Add tag filters to configuration."""
    for tag_group in tags:
        for tag in tag_group:
            command_args.append(f'--tags={tag}')
