"""Localhost-only HTTP bridge to the in-memory EventBus.

Out-of-process callers (e.g. the workspace MCP server, which runs in a
separate process tree from FastAPI) reach BUS via this route — they cannot
import the in-memory singleton directly. Loopback-only; no auth.
"""
from __future__ import annotations

from typing import Any, Optional

from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel

from recoil.api.eventbus import BUS
from recoil.api.schemas.engine import EventSeverity

router = APIRouter()


class _BusEmitRequest(BaseModel):
    scope: str
    severity: EventSeverity
    summary: str
    payload: Optional[dict[str, Any]] = None


@router.post("/internal/bus")
async def internal_bus_emit(
    body: _BusEmitRequest, request: Request
) -> dict[str, bool]:
    client = request.client
    if client is None or client.host != "127.0.0.1":
        raise HTTPException(status_code=403, detail="localhost only")
    BUS.emit_sync(
        body.severity,
        body.scope,
        body.summary,
        payload=body.payload,
    )
    return {"ok": True}


__all__ = ["router"]
