"""
GitHub Actions workflow integration for E2E testing.

Handles workflow execution, environment setup, and integration
between different components of the E2E testing system.
"""

import itertools
import os
import time
from typing import Dict, List

import structlog

logger = structlog.get_logger(__name__)


def validate_workflow_environment(required_vars: List[str]) -> bool:
    """
    Validate workflow environment has required variables.

    Args:
        required_vars: List of required environment variable names.

    Returns:
        bool: True if all variables present, False otherwise.
    """
    missing_vars = [var for var in required_vars if var not in os.environ]

    if missing_vars:
        logger.error("Missing required environment variables", missing=missing_vars)
        return False

    logger.info("Workflow environment validation successful")
    return True


def handle_installation_failure() -> bool:
    """
    Handle installation failure with retry logic.

    Returns:
        bool: True if recovery successful, False otherwise.
    """
    try:
        logger.info("Handling installation failure")

        from .libreoffice_setup import install_libreoffice

        max_retries = 2
        for attempt in range(max_retries + 1):
            logger.debug(
                "Retry attempt", attempt=attempt + 1, max_retries=max_retries + 1
            )
            if install_libreoffice():
                logger.info("Installation retry successful")
                return True
            if attempt < max_retries:
                time.sleep(5)

        logger.error("Installation failed after all retries")
        return False

    except Exception as e:
        logger.error("Error during installation failure handling", error=str(e))
        return False


def prepare_matrix_strategy(
    matrix_config: Dict[str, List[str]],
) -> List[Dict[str, str]]:
    """
    Prepare matrix strategy combinations for testing.

    Args:
        matrix_config: Dictionary with matrix dimensions and values.

    Returns:
        List of matrix combinations.
    """
    try:
        logger.info("Preparing matrix strategy", config=matrix_config)

        keys = list(matrix_config.keys())
        values = [matrix_config[k] for k in keys]
        combinations = [dict(zip(keys, combo)) for combo in itertools.product(*values)]

        logger.info("Matrix strategy prepared", combinations_count=len(combinations))
        return combinations

    except Exception as e:
        logger.error("Error preparing matrix strategy", error=str(e))
        return []


def monitor_workflow_performance(metrics: Dict[str, int]) -> Dict[str, int]:
    """
    Monitor workflow performance metrics.

    Args:
        metrics: Performance metrics dictionary.

    Returns:
        Updated metrics with validation results.
    """
    try:
        logger.info("Monitoring workflow performance", metrics=metrics)

        # Validate performance thresholds
        thresholds = {
            "setup_time": 180,  # 3 minutes
            "execution_time": 300,  # 5 minutes
            "total_time": 600,  # 10 minutes
        }

        performance_ok = True
        for metric, value in metrics.items():
            if metric in thresholds and value > thresholds[metric]:
                logger.warning(
                    "Performance threshold exceeded",
                    metric=metric,
                    value=value,
                    threshold=thresholds[metric],
                )
                performance_ok = False

        metrics["performance_ok"] = performance_ok
        logger.info("Performance monitoring completed", performance_ok=performance_ok)

        return metrics

    except Exception as e:
        logger.error("Error monitoring workflow performance", error=str(e))
        return metrics
