#!/usr/bin/env python3
"""MegaBrain Science — local Python kernel driver.

Implements the Kernel Protocol over newline-delimited JSON on stdio. The Electron
main process (KernelSupervisor) spawns this with `python3 -u kernel_driver.py`,
writes KernelRequest lines to stdin, and reads KernelFrame lines from stdout.

State (the exec namespace) persists across cells for the process lifetime, which
is what makes the kernel "shared with the agent": variables and imports set in one
cell are visible in the next.
"""

import contextlib
import io
import json
import sys
import traceback

# Persistent namespace shared across all cells in this session.
NAMESPACE: dict = {"__name__": "__mb_science__"}


def emit(frame: dict) -> None:
    sys.stdout.write(json.dumps(frame) + "\n")
    sys.stdout.flush()


def run_cell(cell_id: str, code: str) -> None:
    emit({"type": "status", "cellId": cell_id, "state": "busy"})
    stdout, stderr = io.StringIO(), io.StringIO()
    try:
        with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
            # Compile as a module body so top-level expressions still assign/print
            # normally; the persistent NAMESPACE keeps state between cells.
            exec(compile(code, f"<{cell_id}>", "exec"), NAMESPACE)
    except Exception:  # noqa: BLE001 - surface any user error as a stderr stream
        stderr.write(traceback.format_exc())

    out, err = stdout.getvalue(), stderr.getvalue()
    if out:
        emit({"type": "stream", "cellId": cell_id, "kind": "stdout", "data": out})
    if err:
        emit({"type": "stream", "cellId": cell_id, "kind": "stderr", "data": err})
    emit({"type": "status", "cellId": cell_id, "state": "idle"})


def emit_snapshot() -> None:
    import platform

    try:
        import importlib.metadata as md

        packages = sorted(f"{d.metadata['Name']}=={d.version}" for d in md.distributions())
    except Exception:  # noqa: BLE001 - environment listing is best-effort
        packages = []

    emit(
        {
            "type": "snapshot",
            "env": {
                "language": "python",
                "version": platform.python_version(),
                "platform": platform.platform(),
                "packages": packages,
            },
        }
    )


def main() -> None:
    emit({"type": "status", "state": "idle"})
    for raw in sys.stdin:
        line = raw.strip()
        if not line:
            continue
        try:
            request = json.loads(line)
        except json.JSONDecodeError:
            continue

        kind = request.get("type")
        if kind == "execute":
            run_cell(request.get("cellId", ""), request.get("code", ""))
        elif kind == "snapshot":
            emit_snapshot()
        elif kind == "interrupt":
            # Cooperative interrupt is a follow-up; ack for now.
            emit({"type": "status", "state": "idle"})
        # "restart" is handled by the supervisor by killing/respawning us.


if __name__ == "__main__":
    main()
