from __future__ import annotations

from dataclasses import dataclass, field
import time
from typing import Any, Mapping


REQUEST_REF_ID_TAG = "request_ref_id"
LEGACY_REQUEST_ID_TAG = "request_id"


def _normalize_optional_tag_value(value: Any) -> str | None:
    if not isinstance(value, str):
        return None
    normalized = value.strip()
    if not normalized:
        return None
    return normalized


def resolve_request_ref_id(tags: Mapping[str, Any] | None) -> str | None:
    if tags is None:
        return None
    request_ref_id = _normalize_optional_tag_value(tags.get(REQUEST_REF_ID_TAG))
    if request_ref_id is not None:
        return request_ref_id
    return _normalize_optional_tag_value(tags.get(LEGACY_REQUEST_ID_TAG))


@dataclass
class StreamEvent:
    """
    Legacy event payload carrier used by parts of the flow runtime.

    Terminology freeze (WS-0 / M0):
    - request-level external event contract is evolving toward EventEnvelope.
    - StreamEvent remains valid as an internal payload object during migration.
    """
    source: str
    event_type: str
    payload: Any
    tags: dict[str, str] = field(default_factory=dict)
    origin: str | None = None
    timestamp: float = field(default_factory=time.time)

    @property
    def request_ref_id(self) -> str | None:
        return resolve_request_ref_id(self.tags)


__all__ = [
    "StreamEvent",
    "REQUEST_REF_ID_TAG",
    "LEGACY_REQUEST_ID_TAG",
    "resolve_request_ref_id",
]
