﻿import sys
import os
import runpy
import ipaddress
from pathlib import Path

core = Path(sys.argv[1]).resolve()
entry = core / "run_live_desktop_with_copy_and_mic.py"

if not entry.is_file():
    raise RuntimeError("Runtime no encontrado en E:")

# Restricciones solo para este proceso Python.
def is_loopback(host):
    try:
        if isinstance(host, bytes):
            host = host.decode("ascii")
        value = str(host).strip().lower()
        if value in ("localhost", "localhost."):
            return True
        return ipaddress.ip_address(
            value.split("%")[0]
        ).is_loopback
    except Exception:
        return False

def audit(event, args):
    if event == "socket.connect":
        address = args[1] if len(args) > 1 else None
        host = address[0] if isinstance(address, tuple) else None
        if not is_loopback(host):
            raise RuntimeError(
                "PRUEBA_RESTRINGIDA: conexion externa bloqueada"
            )

    elif event == "socket.getaddrinfo":
        host = args[0] if args else None
        if not is_loopback(host):
            raise RuntimeError(
                "PRUEBA_RESTRINGIDA: DNS externo bloqueado"
            )

    elif event == "socket.sendto":
        address = args[-1] if args else None
        host = address[0] if isinstance(address, tuple) else None
        if not is_loopback(host):
            raise RuntimeError(
                "PRUEBA_RESTRINGIDA: envio externo bloqueado"
            )

    elif event in (
        "subprocess.Popen",
        "os.system",
        "os.startfile"
    ):
        raise RuntimeError(
            "PRUEBA_RESTRINGIDA: subproceso bloqueado"
        )

sys.addaudithook(audit)

os.chdir(core)
sys.path.insert(0, str(core))
sys.path.insert(0, str(core / "runtime_v1"))

sys.argv = [str(entry), "--open-ui"]

print("RAIZ_ACTIVA=", core, flush=True)
print("PYTHON_ACTIVO=", sys.executable, flush=True)
print("MODO=GUI_RESTRINGIDA", flush=True)
print("CICLO_PRINCIPAL_SOLICITADO=NO", flush=True)

runpy.run_path(str(entry), run_name="__main__")

