"""GCP helper utilities for authentication and connectivity testing."""

import socket
from typing import Tuple, Optional


def verify_gcp_auth() -> Tuple[str, str]:
    """Verify GCP Application Default Credentials (ADC) are configured.

    Returns:
        Tuple of (project_id, credentials_type)

    Raises:
        ImportError: If google-auth is not installed
        Exception: If ADC is not configured
    """
    try:
        import google.auth
    except ImportError:
        raise ImportError("google-auth not installed. Install with: pip install google-auth")

    credentials, project_id = google.auth.default()
    credentials_type = type(credentials).__name__

    return project_id, credentials_type


def test_collector_connectivity(host: str = "10.164.76.55", ports: Optional[list] = None) -> dict:
    """Test connectivity to OTel Collector ports.

    Args:
        host: Collector hostname or IP address
        ports: List of ports to test (default: [4317, 4318])

    Returns:
        Dictionary mapping port numbers to boolean connectivity status
    """
    if ports is None:
        ports = [4317, 4318]

    results = {}

    for port in ports:
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(3)
            result = sock.connect_ex((host, port))
            sock.close()
            results[port] = result == 0
        except Exception:
            results[port] = False

    return results


def print_gcp_auth_status():
    """Print GCP authentication status in a formatted way."""
    try:
        project_id, creds_type = verify_gcp_auth()
        print("✓ ADC configured")
        print(f"  Project: {project_id}")
        print(f"  Type: {creds_type}")
        return True
    except Exception as e:
        print(f"✗ ADC not configured: {e}")
        print("\nTo configure ADC:")
        print("  gcloud auth application-default login")
        return False


def print_collector_status(host: str = "10.164.76.55"):
    """Print OTel Collector connectivity status in a formatted way."""
    print(f"Testing collector at {host}...\n")

    results = test_collector_connectivity(host)

    http_ok = results.get(4318, False)
    grpc_ok = results.get(4317, False)

    print(f"{'✓' if http_ok else '✗'} OTLP HTTP (4318): {'OPEN' if http_ok else 'CLOSED'}")
    print(f"{'✓' if grpc_ok else '✗'} OTLP gRPC (4317): {'OPEN' if grpc_ok else 'CLOSED'}")

    if not http_ok and not grpc_ok:
        print("\n⚠️  Collector not reachable. Check:")
        print("  1. VPN connection (if outside GKE cluster)")
        print("  2. Firewall rules")
        print("  3. Collector is running")
        return False
    elif http_ok:
        print(f"\n✓ Collector ready: http://{host}:4318")
        return True
    else:
        print(f"\n✓ Collector ready (gRPC only): {host}:4317")
        return True
