"""Core dispatcher: reads session JSON from stdin and fans out to plugins."""

import json
import os
import subprocess
import sys

from .paths import PLUGIN_DIR, SESSION_BASE


def dispatch() -> None:
    """Read session JSON from stdin and fan out to each executable plugin."""
    try:
        raw = sys.stdin.buffer.read()
        session_data = json.loads(raw)
    except Exception:
        return

    session_id = session_data.get("session_id", "unknown")
    sd = SESSION_BASE / session_id
    sd.mkdir(parents=True, exist_ok=True)

    env = os.environ.copy()
    env["STATUSLINE_SESSION_DIR"] = str(sd)

    if not PLUGIN_DIR.is_dir():
        return

    for plugin in sorted(PLUGIN_DIR.iterdir()):
        if not plugin.is_file() or not os.access(plugin, os.X_OK):
            continue
        try:
            subprocess.run(
                [str(plugin)],
                input=raw,
                timeout=5,
                capture_output=True,
                env=env,
            )
        except Exception:
            pass
