"""Shared helpers for ensuring a Cloudflare tunnel and credentials exist."""

from __future__ import annotations

import logging
from pathlib import Path

from .service_install import download_tunnel_credentials, ensure_tunnel_and_service, TunnelInfo
from .state import credentials_path_for_tunnel

logger = logging.getLogger(__name__)


def ensure_tunnel_with_credentials(tunnel_name: str, *, config_path: Path) -> TunnelInfo:
    tunnel_info = ensure_tunnel_and_service(tunnel_name, config_path=config_path)
    credentials_path = Path(credentials_path_for_tunnel(tunnel_info.tunnel_id))
    if credentials_path.exists():
        return tunnel_info

    download_tunnel_credentials(tunnel_info.tunnel_id, credentials_path)
    if not credentials_path.exists():
        raise RuntimeError(
            f"Cloudflare credentials file {credentials_path} still missing after downloading token."
        )
    logger.debug("Cloudflare credentials stored at %s", credentials_path)
    return tunnel_info


__all__ = ["ensure_tunnel_with_credentials"]
