"""
Internal strategy event types for subprocess → main-process communication.

Strategy subprocesses push StrategyEvents via ZMQ PUSH socket.
The main process's StrategyEventBridge receives them via PULL and forwards
them to the user-facing EventPublisher (dexorder/events/publisher.py).
"""
from __future__ import annotations

import json
import time
import uuid
from dataclasses import dataclass, field
from enum import IntEnum


class StrategyEventType(IntEnum):
    """Internal event types produced by strategy subprocesses."""
    STARTED        = 1
    STOPPED        = 2
    HEARTBEAT      = 3
    ORDER_SUBMITTED = 10
    ORDER_FILLED   = 11
    POSITION_UPDATE = 20
    PNL_UPDATE     = 21
    ERROR          = 30
    LOG            = 31


@dataclass
class StrategyEvent:
    """Internal event envelope sent from strategy subprocess to main process."""
    event_type: StrategyEventType
    strategy_name: str
    payload: dict
    timestamp: float = field(default_factory=time.time)
    event_id: str = field(default_factory=lambda: str(uuid.uuid4())[:8])

    def serialize(self) -> bytes:
        return json.dumps({
            "event_type": int(self.event_type),
            "strategy_name": self.strategy_name,
            "payload": self.payload,
            "timestamp": self.timestamp,
            "event_id": self.event_id,
        }).encode()

    @classmethod
    def deserialize(cls, data: bytes) -> "StrategyEvent":
        d = json.loads(data.decode())
        return cls(
            event_type=StrategyEventType(d["event_type"]),
            strategy_name=d["strategy_name"],
            payload=d.get("payload", {}),
            timestamp=d.get("timestamp", time.time()),
            event_id=d.get("event_id", ""),
        )


# IPC endpoint used for strategy subprocess → main process communication
IPC_ENDPOINT = "ipc:///tmp/dexorder-strategy-events.sock"
