"""Type definitions for stdiobus."""

from dataclasses import dataclass, field
from enum import IntEnum, Enum
from typing import TypedDict, Any, Callable, Optional


class BusState(IntEnum):
    """Bus lifecycle states."""
    CREATED = 0
    STARTING = 1
    RUNNING = 2
    STOPPING = 3
    STOPPED = 4


class BackendMode(str, Enum):
    """Backend selection modes."""
    AUTO = "auto"
    NATIVE = "native"
    DOCKER = "docker"


class ListenMode(str, Enum):
    """Transport listen modes."""
    NONE = "none"
    TCP = "tcp"
    UNIX = "unix"


@dataclass
class BusStats:
    """Runtime statistics."""
    messages_in: int = 0
    messages_out: int = 0
    bytes_in: int = 0
    bytes_out: int = 0
    worker_restarts: int = 0
    routing_errors: int = 0
    client_connects: int = 0
    client_disconnects: int = 0


@dataclass
class DockerOptions:
    """Docker backend configuration."""
    image: str = "stdiobus/stdiobus:node20"
    pull_policy: str = "if-missing"  # never, if-missing, always
    engine_path: str = "docker"
    startup_timeout_sec: float = 15.0
    container_name_prefix: str = "stdio-bus"
    extra_args: list[str] = field(default_factory=list)
    env: dict[str, str] = field(default_factory=dict)


@dataclass
class BusOptions:
    """StdioBus configuration options."""
    config_path: str
    backend: BackendMode = BackendMode.AUTO
    timeout_ms: int = 30000
    docker: Optional[DockerOptions] = None


class JsonRpcRequest(TypedDict, total=False):
    """JSON-RPC 2.0 request."""
    jsonrpc: str
    id: str
    method: str
    params: dict[str, Any]


class JsonRpcResponse(TypedDict, total=False):
    """JSON-RPC 2.0 response."""
    jsonrpc: str
    id: str
    result: Any
    error: dict[str, Any]


# Callback types
MessageHandler = Callable[[str], None]
ErrorHandler = Callable[[Exception], None]
