# Copyright (C) 2026 GoodData Corporation

"""Streaming progress event protocol.

This module defines a tiny, stable line-based protocol that external validators can emit
to stdout/stderr while they run. AIDA can parse these lines and forward them to the
MCP client as rich progress updates.

Protocol:
- Each event is a single line starting with EVENT_PREFIX.
- The remainder of the line is a JSON object.
- Tools are encouraged to print their final result as JSON on the last line as well
  (for `external_json` processors).
"""

from __future__ import annotations

from typing import Any, cast

import orjson

EVENT_PREFIX = "AIDA_EVENT "


def format_event(payload: dict[str, object]) -> str:
    """Format a single event line (no trailing newline)."""
    return EVENT_PREFIX + orjson.dumps(payload).decode("utf-8")


def parse_event_line(line: str) -> dict[str, Any] | None:
    """Parse a single line into an event payload if it matches the protocol."""
    raw = line.strip()
    if not raw.startswith(EVENT_PREFIX):
        return None
    json_part = raw.removeprefix(EVENT_PREFIX).strip()
    if not json_part:
        return None
    try:
        obj = orjson.loads(json_part)
    except Exception:
        return None
    if not isinstance(obj, dict):
        return None
    return cast(dict[str, Any], obj)
