"""

    AUTHOR:

        Khushal P Soonderji

    DATE:

        Monday, 23rd Dec., 2024

    OBJECTIVE:

        To receive requests to list tradeable symbols for various stockbrokers like Zerodha.

    REFERENCES:

        N/A

    DOWNLOADS:

        N/A

    NOTES:

        N/A

"""


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


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

# For using Quart:
from quart import Blueprint, current_app, request

# My utils:
from utils_v2.string import json
from utils_v2.api.codes import StatusCodes, HttpCodes
from utils_v2.api.response import ResponseModel
from utils_v2.api.async_quart import (
    set_api_version,
    read_input,
    get_session_info,
    log_request_to_mongo,
    log_chain_to_mongo,
    should_not_be_under_maintenance,
    only_whitelisted_ips,
    limit_rate,
    validate_input,
    handle_cancelled_request
)

# Common:
from shared import constants

# Data Models:
from models.core.auth_token import CoreAuthTokenModel
from models.api.finstitutions.trading.symbols.list import (
    TradingSymbolListRequestHeaders,
    TradingSymbolListRequestData
)
from models.finstitutions.trading.symbols import TradingSymbolListBrokerResponse

# To work with dat and time:
import datetime

# For asynchronous activities:
import asyncio


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


# Related to Quart:
trading_symbols_list_bp = Blueprint("trdng_sym_list", __name__)


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


# --- Nothing Yet


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


@trading_symbols_list_bp.record_once
def init(blueprint_setup_state):

    # This gets called when the blueprint is registered.
    # Consider this to be a one-time setup for the whole blueprint:
    pass


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


@trading_symbols_list_bp.route("/list", methods = ["GET"])
@set_api_version(api_version = "1.0.0")
@read_input(sanitize_headers = False, sanitize_data = False)
@get_session_info(key = "X-Session-Token", session_coro = "get_session")
@log_request_to_mongo(
    attr_name = "logs_mongo",
    project = constants.PROJECT_NAME,
    log_type = constants.MODULE_NAME,
    operation = "trdngSymListReqApi",
    log_input = True,
    log_output = 1,
    sensitive_keys = ["sessionToken", "X-Session-Token", "tokenKey", "tokenKeys"]
)
@log_chain_to_mongo(attr_name = "logs_mongo")
@should_not_be_under_maintenance(attr_name = "is_under_maintenance")
@validate_input(
    header_validator = lambda x: TradingSymbolListRequestHeaders(**x).model_dump(),
    data_validator = lambda x: TradingSymbolListRequestData(**x)
)
@handle_cancelled_request()
async def request_oauth_authorization_url(
        inbound_headers: dict | TradingSymbolListRequestHeaders = None,
        inbound_data: dict | TradingSymbolListRequestData = None,
        inbound_files: dict = None,
        **kwargs
):

    """
    Use this when you want a list of all tradeable symbols from a particular broker.
    :param inbound_headers: auto-extracted by the decorators.
    :param inbound_data: auto-extracted by the decorators.
    :param inbound_files: auto-extracted by the decorators.
    :param kwargs: Any number of extra inputs supplied by the decorators.
    :return: A standard response structure.
    """

    # ┏┓
    # ┃┃┏┓┏┓┏┓┏┓┏┓┏┏┓┏┏
    # ┣┛┛ ┗ ┣┛┛ ┗┛┗┗ ┛┛
    #       ┛

    # If the session token is invalid/expired:
    if kwargs.get("session_info") is None:
        return ResponseModel(
            status_code = StatusCodes.FAILED,
            http_code = HttpCodes.UNAUTHORIZED
        )

    # Get the auth-token:
    auth_token = await current_app.trading_controller.get_token_from_key(
        mongo_data_conn = current_app.data_mongo,
        token_key = inbound_data.tokenKey,
        must_be_active = True
    )
    if not auth_token: return constants.API_RESPONSE_NO_AUTH_TOKEN

    # Start by assuming failure:
    symbol_list = TradingSymbolListBrokerResponse()
    symbol_list.message = f"Invalid/unimplemented client."

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

    if auth_token.client == "zerodhaKite":

        symbol_list = await current_app.zerodha_kite_controller.list_symbols(
            mongo_data_conn = current_app.data_mongo,
            auth_token = auth_token,
            inbound_data = inbound_data
        )

    # ┳┓
    # ┣┫┏┓┏┏┓┏┓┏┓┏┏┓
    # ┛┗┗ ┛┣┛┗┛┛┗┛┗
    #      ┛

    # Handle time data:
    if symbol_list.data:
        symbol_list.data = [s.model_dump() for s in symbol_list.data]
        for d in symbol_list.data:
            expiry_ts = d["expiryTs"]
            if isinstance(expiry_ts, datetime.datetime):
                d["expiryTs"] = expiry_ts.timestamp()

    # Done here:
    return ResponseModel(
        status_code = StatusCodes.OK if symbol_list.success else StatusCodes.FAILED,
        http_code = HttpCodes.SUCCESS if symbol_list.success else HttpCodes.INTERNAL_SERVER_ERROR,
        data = symbol_list.data,
        message = symbol_list.message
    )


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


if __name__ == "__main__":

    pass
