import subprocess
import shutil

def check_k8s(config):
    """
    Checks if kubectl is installed and context is allowed.
    Returns: list of (bool, str, str) - (Success, Message, Level)
    Level can be 'fail', 'warning', 'success'
    """
    if not shutil.which("kubectl"):
        return [(True, "kubectl is not installed", "warning")]

    try:
        result = subprocess.run(
            ["kubectl", "config", "current-context"],
            capture_output=True,
            text=True,
            encoding="utf-8",
            errors="ignore",
            timeout=5
        )
        if result.returncode != 0:
            return [(True, "Could not determine kubectl context", "warning")]
        
        current_context = result.stdout.strip()
        k8s_config = config.get("kubernetes", {})
        allowed_contexts = k8s_config.get("allowed_contexts", [])

        if not allowed_contexts:
            return [(True, f"Kubernetes context: {current_context}", "warning")]

        if current_context in allowed_contexts:
            return [(True, f"Kubernetes context '{current_context}' is allowed", "success")]
        else:
            return [(True, f"Kubernetes context '{current_context}' not in allowed list", "warning")]

    except Exception as e:
        return [(True, f"Error checking Kubernetes: {str(e)}", "warning")]
