#!/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 os
import sys
import traceback

# Render matplotlib to a non-interactive backend so plt.show() never blocks; we capture
# figures ourselves after each cell (see emit_figures). Set before any user import.
os.environ.setdefault("MPLBACKEND", "Agg")

# 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 emit_figures(cell_id: str) -> int:
    """Emit any open matplotlib figures as base64 PNG image frames, then close them.

    This is what makes plots appear inline in the transcript (a science-notebook staple).
    No-op if matplotlib hasn't been used in this session."""
    pyplot = sys.modules.get("matplotlib.pyplot")
    if pyplot is None:
        return 0
    import base64

    count = 0
    try:
        for num in pyplot.get_fignums():
            buf = io.BytesIO()
            pyplot.figure(num).savefig(buf, format="png", bbox_inches="tight", dpi=110)
            data = base64.b64encode(buf.getvalue()).decode("ascii")
            emit({"type": "image", "cellId": cell_id, "mime": "image/png", "data": data})
            count += 1
        pyplot.close("all")
    except Exception:  # noqa: BLE001 - figure capture is best-effort
        pass
    return count


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})
    figures = emit_figures(cell_id)
    if figures:
        # A note in stdout so the (text-only) model knows a figure was produced.
        emit({"type": "stream", "cellId": cell_id, "kind": "stdout",
              "data": f"[{figures} figure(s) displayed]\n"})
    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()
