#!/usr/bin/env python3
"""
System Bus — lightweight event/journal sink for cross-module notifications.

Used by control_api and autonomy_loop to log structured system events
without coupling to any specific storage backend.
"""

from __future__ import annotations

import json
import time
from pathlib import Path


def update_system_section(
    root: Path | str,
    tenant_id: str = "",
    section: str = "",
    patch: dict | None = None,
    source: str = "",
    event_type: str = "",
) -> None:
    """Write a structured event entry to the system bus journal."""
    entry = {
        "ts": time.time(),
        "tenant_id": tenant_id or "default",
        "section": section,
        "source": source,
        "event_type": event_type,
        "patch": patch or {},
    }

    root = Path(root)
    bus_dir = root / "logs"
    bus_dir.mkdir(parents=True, exist_ok=True)

    bus_file = bus_dir / "system_bus.ndjson"
    try:
        with open(bus_file, "a") as f:
            f.write(json.dumps(entry, ensure_ascii=False) + "\n")
    except Exception:
        pass
