import os
import httpx
import requests

PROMETHEUS_URL = os.getenv("PROMETHEUS_URL")

def query_scalar(query: str) -> float | None:
    try:
        r = httpx.get(
            f"{PROMETHEUS_URL}/api/v1/query",
            params={"query": query},
            timeout=5.0,
        )
        r.raise_for_status()
        data = r.json()

        if data["status"] != "success":
            return None

        result = data["data"]["result"]
        if not result:
            return None

        return float(result[0]["value"][1])

    except Exception:
        return None

def query(promql: str):
    r = requests.get(
        f"{PROMETHEUS_URL}/api/v1/query",
        params={"query": promql},
        timeout=3,
    )
    r.raise_for_status()
    return r.json()["data"]["result"]


def get_cpu_usage():
    result = query(
        '100 - (avg by(instance) (rate(node_cpu_seconds_total{mode="idle"}[1m])) * 100)'
    )
    return float(result[0]["value"][1]) if result else 0.0


def get_memory_usage():
    result = query(
        '(1 - (node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes)) * 100'
    )
    return float(result[0]["value"][1]) if result else 0.0


def get_disk_usage():
    result = query(
        '(1 - (node_filesystem_avail_bytes{fstype!~"tmpfs|overlay"} / '
        'node_filesystem_size_bytes{fstype!~"tmpfs|overlay"})) * 100'
    )
    return float(result[0]["value"][1]) if result else 0.0


def get_container_down():
    result = query(
        'count(container_last_seen{job="cadvisor"} < time() - 60)'
    )
    return int(result[0]["value"][1]) if result else 0
