#!/usr/bin/env python3

import sys
import json
import os
from time import time

# Ruta del archivo temporal para almacenar los bytes previos
TEMP_FILE = "/tmp/network_speed.json"


def get_bytes(iface):
    try:
        with open("/proc/net/dev", "r") as f:
            for line in f:
                if iface + ":" in line:
                    parts = line.split()
                    rx_bytes = int(parts[1])
                    tx_bytes = int(parts[9])
                    return rx_bytes, tx_bytes
    except Exception as e:
        print(json.dumps({
            "text": "Error",
            "tooltip": f"Error al leer /proc/net/dev: {e}",
            "class": "network-speed-error"
        }))
        sys.exit(1)
    print(json.dumps({
        "text": "Interfaz no encontrada",
        "tooltip": f"La interfaz '{iface}' no se encontró en /proc/net/dev.",
        "class": "network-speed-error"
    }))
    sys.exit(1)


def format_speed(speed_bytes):
    if speed_bytes >= 1024 * 1024:
        return f"{speed_bytes / (1024 * 1024):.2f} MB/s"
    elif speed_bytes >= 1024:
        return f"{speed_bytes / 1024:.2f} KB/s"
    else:
        return f"{speed_bytes:.2f} B/s"


def main(iface, interval=1):
    current_time = time()
    data = get_bytes(iface)

    if data is None:
        error_message = "Datos de bytes no disponibles."
        print(json.dumps({
            "text": "Error",
            "tooltip": error_message,
            "class": "network-speed-error"
        }))
        sys.exit(1)

    curr_rx, curr_tx = data

    if os.path.exists(TEMP_FILE):
        try:
            with open(TEMP_FILE, "r") as f:
                prev_data = json.load(f)
                prev_time = prev_data.get("time", current_time)
                prev_rx = prev_data.get("rx_bytes", curr_rx)
                prev_tx = prev_data.get("tx_bytes", curr_tx)
        except Exception as e:
            print(json.dumps({
                "text": "Error",
                "tooltip": f"Error al leer el archivo temporal: {e}",
                "class": "network-speed-error"
            }))
            prev_time, prev_rx, prev_tx = current_time, curr_rx, curr_tx
    else:
        prev_time, prev_rx, prev_tx = current_time, curr_rx, curr_tx

    delta_time = current_time - prev_time if current_time - prev_time > 0 else interval
    delta_rx = (curr_rx - prev_rx) / delta_time
    delta_tx = (curr_tx - prev_tx) / delta_time

    rx_speed = format_speed(delta_rx)
    tx_speed = format_speed(delta_tx)

    # Actualizar el archivo temporal con los valores actuales
    try:
        with open(TEMP_FILE, "w") as f:
            json.dump({
                "time": current_time,
                "rx_bytes": curr_rx,
                "tx_bytes": curr_tx
            }, f)
    except Exception as e:
        print(json.dumps({
            "text": "Error",
            "tooltip": f"Error al escribir el archivo temporal: {e}",
            "class": "network-speed-error"
        }))
        sys.exit(1)

    # Crear el objeto JSON para Waybar
    data_output = {
        "text": f"↓ {rx_speed} ↑ {tx_speed}",
        "tooltip": f"Velocidad de descarga: {rx_speed}\nVelocidad de subida: {tx_speed}",
        "class": "network-speed"
    }

    print(json.dumps(data_output))


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(json.dumps({
            "text": "Uso: network_speed.py <interfaz>",
            "tooltip": "Proporciona el nombre de la interfaz de red, por ejemplo: enp3s0",
            "class": "network-speed-error"
        }))
        sys.exit(1)
    iface = sys.argv[1]
    main(iface)
