import os
import time
import base64
import requests
from dotenv import load_dotenv

load_dotenv()

LIBRENMS_URL = os.getenv("LIBRENMS_URL", "https://nms.pixelhosting.nl")

_ports_cache = None

def get_librenms_ports():
    global _ports_cache
    if _ports_cache is None:
        ports_str = os.getenv("LIBRENMS_PORTS", "")
        ports = {}
        if ports_str:
            pairs = ports_str.split(",")
            for pair in pairs:
                if ":" in pair:
                    key, val = pair.split(":", 1)
                    ports[key.strip()] = val.strip()
        _ports_cache = ports
    return _ports_cache

def get_port_id(interface_name):
    return get_librenms_ports().get(interface_name)

def get_timestamp_days_ago(days):
    return int(time.time()) - (days * 86400)

def fetch_graph_base64(port_id, days_ago=None):
    url = f"{LIBRENMS_URL}/graph.php?id={port_id}&type=port_bits&height=200&width=500"
    if days_ago:
        url += f"&from={get_timestamp_days_ago(days_ago)}"
    try:
        response = requests.get(url, timeout=5)
        response.raise_for_status()
        return base64.b64encode(response.content).decode("utf-8")
    except Exception as e:
        print(f"[LibreNMS] Error fetching graph: {e}")
        return None