import subprocess
from modules.mtr_parser import MtrParser

def execute_command_streaming(method, target):
    commands = {
        'ping': ['ping4', '-c', '4', '--', target],
        'ping6': ['ping6', '-c', '4', '--', target],
        'mtr': ['mtr', '--raw', '-n', '-c', '10', '-4', target],
        'mtr6': ['mtr', '--raw', '-n', '-c', '10', '-6', target],
        'traceroute': ['traceroute', '-n', '-4', '--', target],
        'traceroute6': ['traceroute', '-n', '-6', '--', target],
    }

    if method not in commands:
        yield f"Error: Invalid method '{method}'."
        return

    command = commands[method]

    try:
        proc = subprocess.Popen(
            command,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
            bufsize=1,
            universal_newlines=True
        )

        if 'mtr' in method:
            parser = MtrParser()
            for line in iter(proc.stdout.readline, ''):
                if line.strip():
                    parser.update(line)
                    table = parser.render_table()
                    yield f"@@@{table}"
        else:
            for line in iter(proc.stdout.readline, ''):
                yield line
            
        proc.stdout.close()
        proc.wait()
        
    except FileNotFoundError:
        yield f"Error: Command '{command[0]}' not found. Is it installed on the server?"
    except Exception as e:
        yield f"An unexpected error occurred: {e}"