import logging
import subprocess

logger = logging.getLogger(__name__)


def netstat():
    try:
        with open("/proc/net/snmp", "r") as f:
            lines = f.readlines()

        stats = {}

        # Process the lines in pairs (headers and values)
        for i in range(0, len(lines), 2):
            if i + 1 < len(lines):
                header_parts = lines[i].strip().split()
                value_parts = lines[i + 1].strip().split()

                if len(header_parts) == len(value_parts) and len(header_parts) > 1:
                    protocol = header_parts[0].rstrip(":")
                    stats[protocol] = {}

                    # Pair each metric with its value
                    for j in range(1, len(header_parts)):
                        stats[protocol][header_parts[j]] = value_parts[j]
        return stats
    except Exception as e:
        logger.error(f"Error reading /proc/net/snmp: {e}")
        return {"error": str(e)}


def memstat():
    try:
        with open("/proc/meminfo", "r") as f:
            lines = f.readlines()

        stats = {}

        for line in lines:
            parts = line.strip().split(":")
            if len(parts) == 2:
                key = parts[0].strip()
                value = parts[1].strip().split()[0]  # Get the first value (in kB)
                stats[key] = value

        return stats
    except Exception as e:
        logger.error(f"Error reading /proc/meminfo: {e}")
        return {"error": str(e)}


def loadavg():
    try:
        with open("/proc/loadavg", "r") as f:
            line = f.readline().strip()
            parts = line.split()
            if len(parts) >= 5:
                return {
                    "1_min": parts[0],
                    "5_min": parts[1],
                    "15_min": parts[2],
                    "running_processes": parts[3],
                    "total_processes": parts[4],
                }
            else:
                return {"error": "Unexpected format in /proc/loadavg"}
    except Exception as e:
        logger.error(f"Error reading /proc/loadavg: {e}")
        return {"error": str(e)}


def diskstat(data_dir: str):
    try:
        df = subprocess.run(["df", "-h"], capture_output=True, text=True)
        du = subprocess.run(
            f"du -h {data_dir}/*", shell=True, capture_output=True, text=True
        )
    except subprocess.CalledProcessError as e:
        logger.error(f"Error running df or du: {e}")
        return {"error": str(e)}
    return {
        "df": df.stdout,
        "du": du.stdout,
    }
