# target_simulator/gui/external_profiler.py
import socket
import logging

class ExternalProfiler:
    """
    Gestisce la logica di forwarding dei pacchetti su porte dedicate per il profiling esterno.
    """
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.port_a = 0
        self.port_b = 0
        self.socket_a = None
        self.socket_b = None
        self.is_active = False
        self.use_broadcast = False

    def start(self, port_a: int, port_b: int, use_broadcast: bool = False) -> bool:
        """
        Crea i socket e avvia il profiler.
        
        Args:
            port_a: Porta per l'invio del pacchetto raw (inizio elaborazione)
            port_b: Porta per l'invio dopo elaborazione (fine elaborazione)
            use_broadcast: Se True, invia in broadcast invece che solo a localhost
        """
        if self.is_active:
            self.logger.warning("Profiler is already active.")
            return True
        
        self.port_a = port_a
        self.port_b = port_b
        self.use_broadcast = use_broadcast
        
        try:
            self.socket_a = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.socket_a.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            if use_broadcast:
                self.socket_a.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            
            self.socket_b = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            self.socket_b.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            if use_broadcast:
                self.socket_b.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
            
            self.is_active = True
            target = "broadcast" if use_broadcast else "127.0.0.1"
            self.logger.info(f"External Profiler started. Forwarding to {target} on ports A:{port_a}, B:{port_b}")
            return True
        except Exception as e:
            self.logger.error(f"Failed to create sockets for profiling: {e}")
            self.stop()
            return False

    def stop(self):
        """
        Ferma il profiler e chiude i socket.
        """
        if self.socket_a:
            self.socket_a.close()
            self.socket_a = None
        if self.socket_b:
            self.socket_b.close()
            self.socket_b = None
        self.is_active = False
        self.logger.info("External Profiler stopped.")

    def forward_to_port_a(self, raw_bytes: bytes, addr: tuple):
        """
        Callback per la Porta A: inoltra il pacchetto raw se è un messaggio di scenario.
        """
        if not self.is_active or not self.socket_a or len(raw_bytes) <= 6:
            return
            
        flow = raw_bytes[6]
        if flow in (ord('R'), ord('r')):
            try:
                dest_addr = '255.255.255.255' if self.use_broadcast else '127.0.0.1'
                self.socket_a.sendto(raw_bytes, (dest_addr, self.port_a))
            except Exception as e:
                self.logger.error(f"Failed to forward to Port A: {e}")

    def forward_to_port_b(self, raw_bytes: bytes):
        """
        Callback per la Porta B: inoltra il pacchetto raw dopo l'elaborazione.
        """
        if not self.is_active or not self.socket_b or len(raw_bytes) <= 6:
            return
            
        flow = raw_bytes[6]
        if flow in (ord('R'), ord('r')):
            try:
                dest_addr = '255.255.255.255' if self.use_broadcast else '127.0.0.1'
                self.socket_b.sendto(raw_bytes, (dest_addr, self.port_b))
            except Exception as e:
                self.logger.error(f"Failed to forward to Port B: {e}")