"""Small utility helpers shared by the notebook and support modules."""

from __future__ import annotations

import asyncio
import json
from collections.abc import Coroutine
from pathlib import Path
from typing import Any

import pandas as pd


def read_json(path: str | Path) -> Any:
    """Read a JSON file from disk and return the decoded value."""
    return json.loads(Path(path).read_text())


def read_jsonl(path: str | Path) -> list[dict[str, Any]]:
    """Read a JSONL file from disk into a list of dictionaries."""
    return [
        json.loads(line)
        for line in Path(path).read_text().splitlines()
        if line.strip()
    ]


def to_pretty_json(value: Any) -> str:
    """Render a Python value as indented JSON for notebook display."""
    return json.dumps(value, indent=2, ensure_ascii=True)


def records_to_frame(records: list[dict[str, Any]]) -> pd.DataFrame:
    """Convert a list of records into a pandas DataFrame."""
    return pd.DataFrame(records)


def run_async(coro: Coroutine[Any, Any, Any]) -> Any:
    """Run a coroutine in scripts and fail fast inside active notebook loops."""
    try:
        asyncio.get_running_loop()
    except RuntimeError:
        return asyncio.run(coro)
    raise RuntimeError(
        "An event loop is already running. In notebooks, use `await` directly."
    ) from None
