#!flask/bin/python
# -*- coding: utf-8 -*-
#######
# actinia-core - an open source REST API for scalable, distributed, high
# performance processing of geographical data that uses GRASS GIS for
# computational tasks. For details, see https://actinia.mundialis.de/
#
# SPDX-FileCopyrightText: (c) 2016-2023 Sören Gebbert & mundialis GmbH & Co. KG
#
# SPDX-License-Identifier: GPL-3.0-or-later
#
#######

"""
Actinia Core
"""

import os
from .endpoints import create_endpoints
from .health_check import health_check
from .version import init_versions
from actinia_core.core.common.app import flask_app
from actinia_core.core.common.config import global_config, DEFAULT_CONFIG_PATH
from actinia_core.core.common.kvdb_interface import connect
from actinia_core.core.common.process_queue import create_process_queue

__license__ = "GPL-3.0-or-later"
__author__ = "Sören Gebbert"
__copyright__ = "Copyright 2016-2023, Sören Gebbert & mundialis GmbH & Co. KG"
__maintainer__ = "Sören Gebbert"
__email__ = "soerengebbert@googlemail.com"

# if os.environ.get('DEFAULT_CONFIG_PATH'):
#     DEFAULT_CONFIG_PATH = os.environ['DEFAULT_CONFIG_PATH']
if os.path.exists(DEFAULT_CONFIG_PATH) is True and os.path.isfile(
    DEFAULT_CONFIG_PATH
):
    global_config.read(DEFAULT_CONFIG_PATH)

# Create the endpoints based on the global config
create_endpoints()
init_versions()

# TODO: Implement a better error handler
# @flask_app.errorhandler(InvalidUsage)
# def handle_invalid_usage(error):
#    response = error.to_json()
#    response.status_code = error.status_code
#    return response

# Connect the kvdb interfaces
kvdb_args = (global_config.KVDB_SERVER_URL, global_config.KVDB_SERVER_PORT)
if global_config.KVDB_SERVER_PW and global_config.KVDB_SERVER_PW is not None:
    kvdb_args = (*kvdb_args, global_config.KVDB_SERVER_PW)

connect(*kvdb_args)
del kvdb_args

# Create the process queue
create_process_queue(global_config)

# use import to make linter happy (needed to create endpoint)
health_check = health_check

###############################################################################
if __name__ == "__main__":
    # Connect to the database
    flask_app.run(host="0.0.0.0", port=8080, debug=True)
