from __future__ import annotations

import logging

from dataiku import api_client
from flask import Response, g, jsonify, request

logger = logging.getLogger(__name__)


def return_ok(data={}) -> Response:
    content = {"status": "ok", "data": data}
    return jsonify(content)


def return_ko(data={}) -> Response:
    content = {"status": "ko", "data": data}
    return jsonify(content)


def set_auth_identifier():
    try:
        request_headers = dict(request.headers)
        auth_info = api_client().get_auth_info_from_browser_headers(request_headers)
        g.auth_identifier = auth_info["authIdentifier"]
        logger.info(f"Auth identifier set to: {g.auth_identifier}")
    except Exception as e:
        logger.warning(f"Authentication details extraction failed: {e}")
        g.auth_identifier = "unknown"


def strtobool(val):
    """
    Copy of implementation from earlier Python versions. It is not available in python 3.12+.
    Convert a string representation of truth to true (1) or false (0).
    True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values
    are 'n', 'no', 'f', 'false', 'off', and '0'.  Raises ValueError if
    'val' is anything else.
    """
    val = val.lower()
    if val in ("y", "yes", "t", "true", "on", "1"):
        return 1
    elif val in ("n", "no", "f", "false", "off", "0"):
        return 0
    else:
        raise ValueError("invalid truth value %r" % (val,))
