"""kubectl execution using tbot-generated per-cluster kubeconfigs.

tbot generates a kubeconfig for each kubernetes output in its config.
These kubeconfigs use embedded TLS certs (not exec plugin) and work
directly with kubectl.
"""

from __future__ import annotations

import asyncio
import logging
import shlex
from pathlib import Path

from cube_cloud.teleport.tbot_manager import tbot

logger = logging.getLogger(__name__)

MAX_OUTPUT = 512 * 1024  # 512 KB


async def run_kubectl(
    args: list[str], cluster: str | None = None, timeout: float = 60
) -> tuple[str, int]:
    """Run a kubectl command using tbot-generated kubeconfig for the cluster.

    Returns (output, return_code).
    """
    if not tbot.is_ready:
        return "tbot credentials not ready. kubectl is not available.", 1

    if not cluster:
        return "Error: cluster name is required.", 1

    kubeconfig = tbot.get_kubeconfig(cluster)
    if not kubeconfig:
        available = tbot.list_kube_clusters()
        return (
            f"No kubeconfig found for cluster '{cluster}'. "
            f"Available clusters: {', '.join(available) if available else 'none'}"
        ), 1

    cmd = ["kubectl", "--kubeconfig", kubeconfig] + args

    logger.info("kubectl %s (cluster=%s)", " ".join(shlex.quote(a) for a in args), cluster)

    try:
        proc = await asyncio.create_subprocess_exec(
            *cmd,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.STDOUT,
            env={"KUBECONFIG": kubeconfig, "PATH": "/usr/local/bin:/usr/bin:/bin"},
        )

        stdout, _ = await asyncio.wait_for(proc.communicate(), timeout=timeout)
        output = stdout.decode("utf-8", errors="replace")

        if len(output) > MAX_OUTPUT:
            output = output[:MAX_OUTPUT] + "\n\n... (truncated)"

        return output, proc.returncode or 0

    except asyncio.TimeoutError:
        proc.kill()
        return f"kubectl command timed out after {timeout}s", 1
    except FileNotFoundError:
        return "kubectl not found in container.", 1
