"""Trade feedback models."""

from __future__ import annotations

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


@dataclass
class OrderFeedback:
    """Feedback from a simulated or real order execution.

    Attributes
    ----------
    ok : bool
        True if the order was accepted.
    code : int
        Numeric code: 0 = success.
    message : str
        Human-readable description.
    order_id : str | None
        Assigned order ID (simulated or from broker).
    fill_price : float | None
        Filled price (for market orders).
    server_time : str | None
        Server timestamp.
    data : Dict[str, Any] | None
        Additional payload.
    """
    ok: bool
    code: int
    message: str
    order_id: Optional[str] = None
    fill_price: Optional[float] = None
    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)),
            message=str(payload.get("message", "")),
            order_id=payload.get("order_id"),
            fill_price=float(payload["fill_price"]) if payload.get("fill_price") is not None else None,
            server_time=payload.get("server_time"),
            data=payload.get("data"),
        )

    @classmethod
    def success(
        cls,
        order_id: str = "",
        fill_price: float = 0.0,
        message: str = "Order filled",
    ) -> "OrderFeedback":
        return cls(
            ok=True,
            code=0,
            message=message,
            order_id=order_id,
            fill_price=fill_price,
        )

    @classmethod
    def rejection(cls, message: str, code: int = 1) -> "OrderFeedback":
        return cls(ok=False, code=code, message=message)
