from datetime import datetime, timezone
from enum import Enum
from typing import Any
from uuid import uuid4

from pydantic import BaseModel, Field


class SignalSide(str, Enum):
    BUY = "buy"
    SELL = "sell"
    CLOSE = "close"
    FLAT = "flat"


class SignalStatus(str, Enum):
    PENDING = "pending"
    APPROVED = "approved"
    REJECTED = "rejected"
    EXECUTED = "executed"
    FAILED = "failed"


class TradingViewAlert(BaseModel):
    """Payload typique d'une alerte TradingView (JSON personnalisé)."""

    ticker: str = Field(..., description="Symbole TradingView, ex. CME:ES1!")
    action: SignalSide
    price: float | None = None
    quantity: float | None = None
    strategy: str | None = None
    timeframe: str | None = None
    comment: str | None = None
    stop_loss: float | None = None
    take_profit: float | None = None
    raw: dict[str, Any] = Field(default_factory=dict)


class Signal(BaseModel):
    id: str = Field(default_factory=lambda: str(uuid4()))
    received_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
    status: SignalStatus = SignalStatus.PENDING
    alert: TradingViewAlert
    rejection_reason: str | None = None
    execution_note: str | None = None


class ApproveSignalRequest(BaseModel):
    quantity: float | None = None
    note: str | None = None


class RejectSignalRequest(BaseModel):
    reason: str = "Rejected manually"
