import os
import warnings
from urllib.parse import urlparse

# Base URL for aiauto services (path-based routing)
# Single hostname used for all services: API, dashboard, gRPC storage
# Format: scheme://host:port (port is required)
# Example: "https://aiauto.pangyo.ainode.ai:443" or "https://192.168.1.100:8080"
AIAUTO_BASE_URL = os.environ.get("AIAUTO_BASE_URL", "https://aiauto.pangyo.ainode.ai:443")

# Skip SSL certificate verification (for self-signed certificates)
# Set to "true", "1", or "yes" to disable SSL verification
# WARNING: Only use in development/internal environments with self-signed certificates
AIAUTO_INSECURE = os.environ.get("AIAUTO_INSECURE", "").lower() in ("true", "1", "yes")
if AIAUTO_INSECURE:
    warnings.warn(
        "AIAUTO_INSECURE is enabled: SSL certificate verification is disabled. "
        "Do not use in production.",
        stacklevel=1,
    )

# Log level for the aiauto package logger
# Default: INFO (progress + errors), WARNING (errors only), DEBUG (internal details)
AIAUTO_LOG_LEVEL = os.environ.get("AIAUTO_LOG_LEVEL", "INFO").upper()


def parse_grpc_target(base_url: str) -> str:
    """Extract host:port from AIAUTO_BASE_URL for grpc.insecure_channel() / grpc.secure_channel().

    gRPC channel target must be "host:port" without scheme.
    Example: "https://aiauto.pangyo.ainode.ai:443" -> "aiauto.pangyo.ainode.ai:443"
             "http://localhost:8080" -> "localhost:8080"

    Args:
        base_url: Full URL with scheme (http:// or https://)

    Returns:
        "host:port" string for gRPC channel creation

    Raises:
        ValueError: If base_url is missing scheme or hostname
    """
    parsed = urlparse(base_url)
    if not parsed.hostname:
        raise ValueError(f"AIAUTO_BASE_URL must have a hostname, got: {base_url!r}")
    if not parsed.scheme:
        raise ValueError(f"AIAUTO_BASE_URL must have http:// or https:// scheme, got: {base_url!r}")
    port = parsed.port or (443 if parsed.scheme == "https" else 80)
    return f"{parsed.hostname}:{port}"


def is_secure_url(base_url: str) -> bool:
    """Check if AIAUTO_BASE_URL uses https:// (TLS).

    Args:
        base_url: Full URL with scheme

    Returns:
        True if https://, False if http://
    """
    return urlparse(base_url).scheme == "https"
