"""tbot application certificate management.

tbot can generate short-lived certificates for Teleport-registered apps,
enabling server-side access without the user running `tsh app login`.
"""

from __future__ import annotations

import logging
from pathlib import Path

from cube_cloud.teleport.tbot_manager import tbot

logger = logging.getLogger(__name__)


def get_app_cert(app_name: str) -> dict | None:
    """Get app certificate paths if available.

    Returns dict with cert/key/ca paths, or None if not available.
    tbot output structure: {data_dir}/app-{app_name}/tlscert, tls.key, tls.cas
    """
    cert_dir = tbot.get_app_cert_dir(app_name)
    if not cert_dir:
        return None

    cert = cert_dir / "tlscert"
    key = cert_dir / "tls.key"
    ca = cert_dir / "tls.cas"

    if not cert.exists() or not key.exists():
        logger.warning("App cert files missing for %s in %s", app_name, cert_dir)
        return None

    return {
        "cert": str(cert),
        "key": str(key),
        "ca": str(ca) if ca.exists() else None,
    }
