"""HTTP API implementation.
"""

import sys

from docopt import docopt
from flask import Flask
from flask import make_response
from flask import request
import numpy as np
import ujson
from werkzeug.exceptions import BadRequest

from . import __version__
from .fit import activate as activate_base
from .fit import fit as fit_base
from .interfaces import PredictError
from .util import args_from_config
from .util import get_config
from .util import get_metadata
from .util import initialize_config
from .util import logger
from .util import memory_usage_psutil
from .util import PluggableDecorator
from .util import process_store
from .util import run_job
from .util import resolve_dotted_name

app = Flask(__name__)


def make_ujson_response(obj, status_code=200):
    """Encodes the given *obj* to json and wraps it in a response.

    :return:
      A Flask response.
    """
    json_encoded = ujson.encode(obj, ensure_ascii=False)
    resp = make_response(json_encoded)
    resp.mimetype = 'application/json'
    resp.content_type = 'application/json; charset=utf-8'
    resp.status_code = status_code
    return resp


class PredictService:
    """A default :class:`palladium.interfaces.PredictService`
    implementation.

    Aims to work out of the box for the most standard use cases.
    Allows overriding of specific parts of its logic by using granular
    methods to compose the work.
    """
    types = {
        'float': float,
        'int': int,
        'str': str,
        'bool': lambda x: x.lower() == 'true',
        }

    def __init__(
        self,
        mapping,
        params=(),
        entry_point='/predict',
        decorator_list_name='predict_decorators',
        predict_proba=False,
        unwrap_sample=False,
        **kwargs
    ):
        """
        :param mapping:
          A list of query parameters and their type that should be
          included in the request.  These will be processed in the
          :meth:`sample_from_data` method to construct a sample
          that can be used for prediction.  An example that expects
          two request parameters called ``pos`` and ``neg`` that are
          both of type str::

            { ...
              'mapping': [('pos', 'str'), ('neg', 'str')]
            ... }

        :param params:
          Similarly to *mapping*, this is a list of name and type of
          parameters that will be passed to the model's
          :meth:`~palladium.interfaces.Model.predict` method as keyword
          arguments.

        :param predict_proba:
          Instead of returning a single class (the default), when
          *predict_proba* is set to true, the result will instead
          contain a list of class probabilities.