"""
Environment setup and validation for GitHub Actions E2E testing.

Handles Python environment configuration, dependency installation,
and GitHub Actions environment validation.
"""

import subprocess
import os
import structlog
from typing import List, Dict
from pathlib import Path

logger = structlog.get_logger(__name__)


def setup_python_environment() -> bool:
    """
    Set up Python environment with required dependencies.

    Returns:
        bool: True if setup successful, False otherwise.
    """
    try:
        logger.info("Setting up Python environment")

        # Upgrade pip
        pip_upgrade_cmd = ["python", "-m", "pip", "install", "--upgrade", "pip"]
        subprocess.run(
            pip_upgrade_cmd, capture_output=True, text=True, timeout=120, check=True
        )
        logger.debug("Pip upgraded successfully")

        # Install from pyproject.toml
        install_cmd = ["pip", "install", "-e", ".[dev]"]
        try:
            subprocess.run(
                install_cmd, capture_output=True, text=True, timeout=300, check=True
            )
            logger.info("Dependencies installed from pyproject.toml")
        except subprocess.CalledProcessError:
            logger.warning(
                "pyproject.toml install failed, installing core dependencies"
            )
            core_deps = [
                "pytest>=7.4.0",
                "lxml>=4.9.0",
                "Pillow>=10.0.0",
                "structlog>=23.1.0",
            ]
            install_cmd = ["pip", "install"] + core_deps
            subprocess.run(
                install_cmd, capture_output=True, text=True, timeout=300, check=True
            )
            logger.info("Core dependencies installed")

        return True

    except subprocess.CalledProcessError as e:
        logger.error(
            "Python environment setup failed", returncode=e.returncode, stderr=e.stderr
        )
        return False
    except subprocess.TimeoutExpired:
        logger.error("Python environment setup timed out")
        return False
    except Exception as e:
        logger.error("Unexpected error during Python environment setup", error=str(e))
        return False


def validate_github_environment() -> bool:
    """
    Validate GitHub Actions environment variables and setup.

    Returns:
        bool: True if environment is valid, False otherwise.
    """
    required_env_vars = [
        "GITHUB_WORKSPACE",
        "GITHUB_REPOSITORY",
        "GITHUB_SHA",
        "GITHUB_REF",
    ]

    missing_vars = []
    for var in required_env_vars:
        if var not in os.environ:
            missing_vars.append(var)

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

    # Validate workspace directory exists
    workspace = os.environ.get("GITHUB_WORKSPACE")
    if workspace and not Path(workspace).exists():
        logger.error("GitHub workspace directory does not exist", workspace=workspace)
        return False

    logger.info(
        "GitHub environment validation successful",
        workspace=workspace,
        repository=os.environ.get("GITHUB_REPOSITORY"),
    )
    return True


def validate_requirements_file(requirements_path: str = "pyproject.toml") -> bool:
    """
    Validate that pyproject.toml exists and has required dependencies.

    Args:
        requirements_path: Path to pyproject.toml (legacy name kept for compat).

    Returns:
        bool: True if valid, False otherwise.
    """
    try:
        path = Path(requirements_path)
        if not path.exists():
            logger.error("Project file does not exist", path=requirements_path)
            return False

        logger.info("Project file validation completed", path=requirements_path)
        return True

    except Exception as e:
        logger.error("Error validating project file", error=str(e))
        return False


def setup_python_dependencies(requirements: List[str]) -> bool:
    """
    Install specific Python dependencies.

    Args:
        requirements: List of package requirements.

    Returns:
        bool: True if installation successful, False otherwise.
    """
    try:
        logger.info("Installing Python dependencies", count=len(requirements))

        install_cmd = ["pip", "install"] + requirements
        subprocess.run(
            install_cmd, capture_output=True, text=True, timeout=300, check=True
        )

        logger.info("Dependencies installed successfully", packages=requirements)
        return True

    except subprocess.CalledProcessError as e:
        logger.error(
            "Dependency installation failed", returncode=e.returncode, stderr=e.stderr
        )
        return False
    except Exception as e:
        logger.error("Unexpected error during dependency installation", error=str(e))
        return False


def validate_python_version() -> bool:
    """
    Validate Python version meets requirements.

    Returns:
        bool: True if version is compatible, False otherwise.
    """
    try:
        import sys

        major, minor = sys.version_info[:2]
        min_version = (3, 9)

        if (major, minor) >= min_version:
            logger.info(
                "Python version validation successful", version=f"{major}.{minor}"
            )
            return True
        else:
            logger.error(
                "Python version too old",
                current=f"{major}.{minor}",
                required=f"{min_version[0]}.{min_version[1]}",
            )
            return False

    except Exception as e:
        logger.error("Error validating Python version", error=str(e))
        return False


def get_environment_info() -> Dict:
    """
    Get comprehensive environment information.

    Returns:
        dict: Environment information.
    """
    info = {
        "python_version": None,
        "pip_version": None,
        "github_environment": False,
        "workspace": None,
        "repository": None,
        "installed_packages": [],
    }

    try:
        import sys

        # Python version
        info["python_version"] = (
            f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
        )

        # Pip version
        try:
            pip_result = subprocess.run(
                ["pip", "--version"], capture_output=True, text=True, timeout=10
            )
            if pip_result.returncode == 0:
                info["pip_version"] = pip_result.stdout.strip()
        except Exception:
            pass

        # GitHub environment
        info["github_environment"] = validate_github_environment()
        info["workspace"] = os.environ.get("GITHUB_WORKSPACE")
        info["repository"] = os.environ.get("GITHUB_REPOSITORY")

        # Installed packages
        try:
            list_result = subprocess.run(
                ["pip", "list", "--format=freeze"],
                capture_output=True,
                text=True,
                timeout=30,
            )
            if list_result.returncode == 0:
                info["installed_packages"] = list_result.stdout.strip().split("\n")
        except Exception:
            pass

        logger.info("Environment information gathered", info=info)

    except Exception as e:
        logger.error("Error gathering environment information", error=str(e))

    return info
