from typing import Any
from app.api.v1.crypto_api import encrypt_data
import json
from fastapi.responses import PlainTextResponse

def custom_response(code: int, data: Any = None, key: Any = None, message: str = "", plain_text: bool = False, **kwargs):
    """
    Standardized response function for API endpoints.
    If plain_text=True, returns only the encrypted string (not a JSON object).
    """
    if data is None:
        data = []

    if plain_text:
        # Return only the encrypted string (not a JSON object)
        if isinstance(data, str):
            return data
        return encrypt_data(json.dumps(data))

    if key:
        data = {"code": code, "data": data, "token": key, "message": message}
    else:
        data = {"code": code, "data": data, "message": message}
        
    if kwargs:
        data.update(kwargs)
    encrypted_response_string = encrypt_data(json.dumps(data))
    return encrypted_response_string