from __future__ import annotations

import logging
from functools import wraps
from typing import Type

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

from config_utils import strtobool as _strtobool

logger = logging.getLogger(__name__)


def strtobool(val: str) -> int:
    return _strtobool(val)


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 validate_params(model: Type[BaseModel]):
    """
    Decorator to validate request JSON body against a Pydantic model.
    Injects the validated model instance as 'params' argument to the decorated function.
    """
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            json_data = request.get_json()
            
            params = model(**json_data)
            kwargs['params'] = params
            return f(*args, **kwargs)

        return decorated_function
    return decorator


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"
