import os

from flask import Flask, jsonify
from flask_restful import Api

from blackant.utils.logging import get_logger
from blackant.utils.initialization import process_run_mode, initialize_logging
from healthcheck import HealthCheckResource
from task.resource import TaskResource

DEBUG_MODE, RELEASE_MODE = process_run_mode()

APP = Flask(__name__)

gunicorn_app = APP

API = Api(APP)

initialize_logging(APP, config_file_path="logging.ini")

API.add_resource(TaskResource, "/task", "/task/<task_id>")
API.add_resource(HealthCheckResource, "/healthcheck")


DEFAULT_ERROR_LOGGER = get_logger("default_error_handler")


@APP.errorhandler(Exception)
def default_error_handler(exc):
    """Default error handler"""
    DEFAULT_ERROR_LOGGER.exception(exc)
    return jsonify(message=str(exc)), getattr(exc, "code", 500)


if __name__ == "__main__":
    logger = get_logger("server")
    logger.info("Calculation: %s", os.environ["CALCULATION_NAME"])
    APP.run(debug=DEBUG_MODE, host="0.0.0.0", port=int(os.environ["SERVER_PORT"]))
