using System.Net.NetworkInformation;
using System.Net.Sockets;
using NexusShell.Models;

namespace NexusShell.Services;

public sealed class NexusNetworkInfoService
{
    public NexusNetworkInfoSnapshot Capture()
    {
        var online = NetworkInterface.GetIsNetworkAvailable();
        var iface = GetPrimaryInterface();
        if (iface is null)
        {
            return new NexusNetworkInfoSnapshot
            {
                ActiveNetwork = online ? "Ingen aktiv forbindelse" : "Offline",
                IpAddress = "—",
                SignalStrength = online ? "—" : "Ingen signal",
                IsOnline = online,
            };
        }

        return new NexusNetworkInfoSnapshot
        {
            ActiveNetwork = FormatNetworkName(iface),
            IpAddress = GetPrimaryIp(iface),
            SignalStrength = EstimateSignal(iface),
            IsOnline = online,
        };
    }

    private static NetworkInterface? GetPrimaryInterface() =>
        NetworkInterface.GetAllNetworkInterfaces()
            .Where(static n => n.OperationalStatus == OperationalStatus.Up)
            .Where(static n => n.NetworkInterfaceType is not (NetworkInterfaceType.Loopback or NetworkInterfaceType.Tunnel))
            .Where(static n => n.GetIPProperties().GatewayAddresses.Count > 0 || n.Speed > 0)
            .OrderByDescending(static n => n.Speed)
            .ThenByDescending(static n => n.GetIPProperties().GatewayAddresses.Count)
            .FirstOrDefault();

    private static string FormatNetworkName(NetworkInterface iface)
    {
        var name = string.IsNullOrWhiteSpace(iface.Name) ? iface.Description : iface.Name;
        return iface.NetworkInterfaceType switch
        {
            NetworkInterfaceType.Wireless80211 => $"Wi‑Fi — {name}",
            NetworkInterfaceType.Ethernet => $"Ethernet — {name}",
            _ => name,
        };
    }

    private static string GetPrimaryIp(NetworkInterface iface)
    {
        var address = iface.GetIPProperties().UnicastAddresses
            .FirstOrDefault(static a => a.Address.AddressFamily == AddressFamily.InterNetwork)?.Address;
        return address?.ToString() ?? "—";
    }

    private static string EstimateSignal(NetworkInterface iface)
    {
        if (iface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
        {
            return "Wi‑Fi aktiv (signal ikke tilgængeligt i POC)";
        }

        if (iface.Speed > 0)
        {
            var gbps = iface.Speed / 1_000_000_000d;
            if (gbps >= 1)
            {
                return $"Link {gbps:0.#} Gbps";
            }

            var mbps = iface.Speed / 1_000_000d;
            return mbps >= 1 ? $"Link {mbps:0} Mbps" : "Tilsluttet";
        }

        return "Tilsluttet";
    }
}
