"""
Discovers local devices via ARP scanning.
By default, all devices are inspected.
When the packets are received by the packet processor, they will be added to the devices table.

"""

import logging
import asyncio
from multiprocessing import Queue
from scapy.packet import Packet
from scapy.sendrecv import sendp
from scapy.layers.l2 import Ether, ARP
from scapy.all import conf

from shared.networking_helpers import get_default_route

logger = logging.getLogger(__name__)


async def arp_scan(packet_queue: "Queue[Packet | str] | None") -> None:
    # Sends an ARP request to every IP address on the network
    default_route = get_default_route()
    subnet = default_route.subnet
    host_mac = default_route.host_mac

    if subnet.num_addresses > 256:
        logger.info("Subnet is too large for ARP scanning, skipping.")
        return

    logger.info(f"Scanning {subnet.num_addresses} IP addresses.")

    for ip in subnet.hosts():
        arp_pkt = Ether(src=host_mac, dst="ff:ff:ff:ff:ff:ff") / ARP(
            pdst=str(ip), hwsrc=host_mac, hwdst="ff:ff:ff:ff:ff:ff"
        )
        sendp(arp_pkt, iface=conf.iface, verbose=0)

    await asyncio.sleep(5)

    if packet_queue is not None:
        packet_queue.put("FLUSH")
