from datetime import datetime
from typing import List, Optional, Any
from uuid import UUID
from ninja import Schema
from pydantic import field_serializer, model_validator


class MarketOptionSchema(Schema):
    uuid: UUID
    text: str
    total_bets: int = 0

    @field_serializer("uuid")
    def serialize_uuid(self, value: UUID) -> str:
        return str(value)


class MarketListSchema(Schema):
    uuid: UUID
    title: str
    description: str
    status: str
    end_date: datetime
    multiplier: float = 1.0
    created_at: datetime
    options: List[MarketOptionSchema]
    winning_option: Optional[MarketOptionSchema] = None

    @field_serializer("uuid")
    def serialize_uuid(self, value: UUID) -> str:
        return str(value)


class ResolveMarketSchema(Schema):
    winning_option_uuid: str


class UserBetCreateSchema(Schema):
    option_uuid: str
    amount: int


class UserBetSchema(Schema):
    uuid: UUID
    amount: int
    created_at: datetime
    option: MarketOptionSchema
    market: Optional[MarketListSchema] = None

    @field_serializer("uuid")
    def serialize_uuid(self, value: UUID) -> str:
        return str(value)

    @model_validator(mode="before")
    @classmethod
    def resolve_market_from_option(cls, data: Any) -> Any:
        if hasattr(data, "option") and hasattr(data.option, "market"):
            data.market = data.option.market
        return data
