﻿import ast
import os
import runpy
import sys
import types
from pathlib import Path

core = Path(sys.argv[1]).resolve()
brain = core / "artifacts" / "brain_host" / "brain_host_tls.py"

source = brain.read_text(encoding="utf-8-sig")
tree = ast.parse(source, filename=str(brain))

# Validar el contrato del monitor antes de neutralizarlo.
guards = [
    n for n in tree.body
    if isinstance(n, ast.If)
    and "__name__" in ast.unparse(n.test)
    and "__main__" in ast.unparse(n.test)
]

if len(guards) != 1:
    raise RuntimeError("Punto de entrada inesperado")

main_text = ast.unparse(guards[0])

if (
    "start_continuous_health_monitor" not in main_text
    or "app.system_health.runtime_monitor" not in main_text
):
    raise RuntimeError("Contrato de monitor no reconocido")

if os.environ.get("BRAIN_HOST_BIND_ADDRESS") != "127.0.0.1":
    raise RuntimeError("Bind no autorizado")

if os.environ.get("BRAIN_HOST_PORT") != "18443":
    raise RuntimeError("Puerto no autorizado")

# No admitir conexiones salientes ni procesos adicionales
# iniciados por las APIs Python auditadas.
def audit(event, args):
    if event == "socket.bind":
        address = args[1] if len(args) > 1 else None
        if not isinstance(address, tuple) or address[0] != "127.0.0.1":
            raise PermissionError("BIND_FUERA_DE_LOOPBACK_BLOQUEADO")

    if event in (
        "socket.connect",
        "socket.connect_ex",
        "subprocess.Popen",
        "os.system",
        "os.startfile",
        "os.exec",
        "os.posix_spawn",
    ):
        raise PermissionError("OPERACION_NO_AUTORIZADA: " + event)

    if event == "open" and args:
        filename = args[0]
        if isinstance(filename, (str, bytes)):
            value = os.fsdecode(filename).lower().replace("/", "\\")
            if (
                "c:\\xampp\\htdocs\\digital optimus" in value
                or "c:\\optimusprojects" in value
            ):
                raise PermissionError("PROYECTO_ANTIGUO_BLOQUEADO")

sys.addaudithook(audit)

# Sustituir exclusivamente en memoria el monitor automático.
shim = types.ModuleType("app.system_health.runtime_monitor")

def start_monitor_stub():
    print("MONITOR_STUB_STARTED=SI", flush=True)
    return None

def stop_monitor_stub():
    print("MONITOR_STUB_STOPPED=SI", flush=True)
    return None

shim.start_continuous_health_monitor = start_monitor_stub
shim.stop_continuous_health_monitor = stop_monitor_stub

sys.modules["app.system_health.runtime_monitor"] = shim

os.chdir(core)
sys.path.insert(0, str(core))
sys.path.insert(0, str(brain.parent))
sys.argv = [str(brain)]

print("BRAIN_SOURCE=", brain, flush=True)
print("PYTHON=", sys.executable, flush=True)
print("BIND=127.0.0.1", flush=True)
print("PORT=18443", flush=True)
print("MONITOR_REAL_INICIADO_POR_ESTE_LANZADOR=NO", flush=True)

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