from __future__ import annotations

try:
    from IPython import get_ipython  # type: ignore[import-not-found]
except Exception:  # pragma: no cover
    get_ipython = None  # type: ignore[assignment]


def read_ipython_code_cells(*, max_cells: int | None = None) -> list[str]:
    """
    Pull recent inputs from IPython history.

    This is best-effort. Some environments don't store all history.
    """
    if get_ipython is None:
        raise RuntimeError(
            "IPython is not available. "
            "Install neurobyte[ipython] or use export_notebook()."
        )

    ip = get_ipython()
    if ip is None or not hasattr(ip, "history_manager"):
        raise RuntimeError("No active IPython session found.")

    inputs: list[str] = []
    # (session, line, input) tuples
    for _session, _line, text in ip.history_manager.get_range():  # type: ignore[attr-defined]
        t = (text or "").rstrip()
        if t and not t.startswith("%") and not t.startswith("!"):
            inputs.append(t)

    if max_cells is not None:
        return inputs[-max_cells:]
    return inputs
