"""

    AUTHOR:

        Khushal P Soonderji

    DATE:

        Monday, 23rd Dec., 2024.

    OBJECTIVE:

        To provide a structure to receive symbol/instrument listing requests for stock trading brokers like Zerodha.

    REFERENCES:

        N/A

    DOWNLOADS:

        N/A

"""


#   *****************************************************************************************************************
#  *****                                                                                                          ****
# ***                                                   IMPORT                                                      ***
#  *****                                                                                                          ****
#   *****************************************************************************************************************


# To make sibling directories accessible for imports:
import sys
sys.path.append(".")
sys.path.append("..")

# For making data behaviour_models:
from pydantic import BaseModel, Field, field_validator, PastDatetime, model_validator, AwareDatetime
from typing import Optional, Literal, Union, List

# My utils:
from utils_v2.string import json
from utils_v2.string import regex
from utils_v2.date_time import date_time

# Other models:
from models.finstitutions.trading.symbols import TradingSymbol

# To work with date and time:
import datetime


#   *****************************************************************************************************************
#  *****                                                                                                          ****
# ***                                           MACROS / ONE-TIME INIT                                              ***
#  *****                                                                                                          ****
#   *****************************************************************************************************************


# RegEx Patterns:
REGEX_SESSION_TOKEN = r"^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$"


#   *****************************************************************************************************************
#  *****                                                                                                          ****
# ***                                                VARIABLES                                                      ***
#  *****                                                                                                          ****
#   *****************************************************************************************************************


# --- Nothing Yet


#   *****************************************************************************************************************
#  *****                                                                                                          ****
# ***                                                  FUNCTIONS                                                    ***
#  *****                                                                                                          ****
#   *****************************************************************************************************************


class TradingSymbolListBrokerResponse(BaseModel):

    success: bool = Field(
        description = "whether, or not, the symbol list request was successful",
        default = False,
        frozen = False
    )

    message: str = Field(
        description = "a brief message to help debug in failed cases",
        default = "",
        frozen = False
    )

    data: List[TradingSymbol] | None = Field(
        description = "the actual response from the broker with his list of tradeable symbols",
        default = None,
        frozen = False
    )

    exception: Exception | None = Field(
        description = "if something goes wrong, the exception will be held here",
        default = None,
        frozen = False
    )

    # ┏┓    ┏•
    # ┃ ┏┓┏┓╋┓┏┓
    # ┗┛┗┛┛┗┛┗┗┫
    #          ┛

    class Config:
        extra = "forbid"
        arbitrary_types_allowed = True


# ---------------------------------------------------------------------------------------------------------------------


class TradingSymbolListRequestHeaders(BaseModel):

    sessionToken: str = Field(
        description = "the session token of the user who is requesting the service",
        pattern = REGEX_SESSION_TOKEN,
        frozen = True,
        alias = "X-Session-Token"
    )

    # ┏┓    ┏•
    # ┃ ┏┓┏┓╋┓┏┓
    # ┗┛┗┛┛┗┛┗┗┫
    #          ┛

    class Config:
        extra = "allow"

    def model_dump(self, *args, **kwargs):
        return super().model_dump(*args, by_alias = True, **kwargs)


# ---------------------------------------------------------------------------------------------------------------------


class TradingSymbolListRequestData(BaseModel):

    tokenKey: str = Field(
        description = "the token identifier(s) that tell you which auth-tokens were used for fetching those messages",
        frozen = True
    )

    exchanges: str | None | List[str | None] = Field(
        description = (
            "the exchange whose tradeable symbols are of interest to us; "
            "wherever null is not applicable, a default value will be taken"
        ),
        default = None,
        frozen = True,
        examples = ["NSE", "NFO", "BSE", "BFO", "MCX", "CDS", "BCD"]
    )

    # ┏┓    ┏•
    # ┃ ┏┓┏┓╋┓┏┓
    # ┗┛┗┛┛┗┛┗┗┫
    #          ┛

    class Config:
        extra = "forbid"

    # ┓┏  ┓• ┓   •
    # ┃┃┏┓┃┓┏┫┏┓╋┓┏┓┏┓
    # ┗┛┗┻┗┗┗┻┗┻┗┗┗┛┛┗

    @field_validator("exchanges", mode = "before")
    def ensure_list(cls, value):
        if isinstance(value, str):
            if regex.match(
                    text = value,
                    pattern = r"\[.*\]",
                    dot_all = True
            ): value = json.from_string(value)
            else: value = [value]
        elif isinstance(value, list): pass
        else: value = None
        return value


#   *****************************************************************************************************************
#  *****                                                                                                          ****
# ***                                               MAIN PROGRAM                                                    ***
#  *****                                                                                                          ****
#   *****************************************************************************************************************


if __name__ == "__main__":

    pass
