"""Feedback models for trade execution and messaging."""

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional


@dataclass
class OrderFeedback:
    """Feedback from an order or signal execution attempt.

    Attributes
    ----------
    ok : bool
        True if execution was accepted / successful.
    code : int
        HTTP-style code: 0 for success, > 0 for error.
    message : str
        Human-readable result message.
    server_time : str | None
        Server timestamp of the feedback.
    data : Dict[str, Any] | None
        Additional response payload.
    """

    ok: bool
    code: int
    message: str
    server_time: Optional[str] = None
    data: Optional[Dict[str, Any]] = None

    @classmethod
    def from_api(cls, payload: Dict[str, Any]) -> "OrderFeedback":
        return cls(
            ok=bool(payload.get("ok", False)),
            code=int(payload.get("code", 0) if isinstance(payload.get("code"), int) else 0),
            message=str(payload.get("message", "")),
            server_time=payload.get("server_time"),
            data=payload if isinstance(payload, dict) else None,
        )

    @classmethod
    def success(cls, message: str = "OK", data: Dict[str, Any] | None = None) -> "OrderFeedback":
        return cls(ok=True, code=0, message=message, server_time=None, data=data)

    @classmethod
    def failure(cls, code: int, message: str) -> "OrderFeedback":
        return cls(ok=False, code=code, message=message, server_time=None, data=None)


@dataclass
class MessageFeedback:
    """Feedback for a general webhook / message dispatch."""

    ok: bool
    message: str
    delivered_at: Optional[str] = None

    @classmethod
    def from_api(cls, payload: Dict[str, Any]) -> "MessageFeedback":
        return cls(
            ok=bool(payload.get("ok", False)),
            message=str(payload.get("message", "")),
            delivered_at=payload.get("delivered_at"),
        )


@dataclass
class SignalFeedback:
    """Feedback from a signal dispatch."""

    ok: bool
    signal_id: Optional[str] = None
    message: str = ""
    server_time: Optional[str] = None
    data: Optional[Dict[str, Any]] = None

    @classmethod
    def from_api(cls, payload: Dict[str, Any]) -> "SignalFeedback":
        return cls(
            ok=bool(payload.get("ok", False)),
            signal_id=payload.get("signal_id"),
            message=str(payload.get("message", "")),
            server_time=payload.get("server_time"),
            data=payload.get("data"),
        )
