import logging
import sys
import time
from kubernetes import client, config

logger = logging.getLogger(__name__)

KUBERNETES_CONGIGURED = False

try:
    config.load_kube_config("/home/ubuntu/.kube/config")
    KUBERNETES_CONGIGURED = True
except Exception as e:
    logger.error(f"Error loading kube config: {e}")

v1 = client.CoreV1Api()

pod_info_dict = {}


def update_pod_info(namespace="default"):
    """Queries Kubernetes API to get pod names and IPs."""
    global pod_info_dict

    if not KUBERNETES_CONGIGURED:
        return
    
    try:
        pods = v1.list_namespaced_pod(namespace)
        pod_info_dict.clear()
        for pod in pods.items:
            pod_name = pod.metadata.name
            pod_ip = pod.status.pod_ip
            pod_info_dict[pod_ip] = pod_name
        logger.info(f"Updated information of {len(pod_info_dict)} pods")
        for ip, name in pod_info_dict.items():
            logger.info(f"Pod Name: {name} ({ip})")
    except Exception as e:
        logger.error(f"Error querying Kubernetes: {e}")

def get_pod_name_by_ip(pod_name):
    """Retrieves the IP of a pod from the using the pod's name."""
    return pod_info_dict.get(pod_name, None)
