# add modules folder to interpreter path
import sys
import os
import prance
from pathlib import Path

modules_path = '../../../modules/'
if os.path.exists(modules_path):
    sys.path.insert(1, modules_path)

# init logging to file
import logging
LOG_FORMAT = ('%(levelname) -5s %(asctime)s %(name)s:%(funcName) -35s %(lineno) -5d:  %(message)s')
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
LOGGER = logging.getLogger(__name__)

#############################
import connexion
from security import swagger_util
from env_info import is_running_locally, get_resources_path

from database.repository import Repository
from messaging.MessageHandler import MessageHandler
from messaging.ReconnectingMessageManager import ReconnectingMessageManager
from messaging.rest_fetcher import RestFetcher
from flask import request
from flask import redirect

# init message handler
message_handler:MessageHandler = None
def message_received_callback(channel, method, properties, body):
    message_handler.handle_generic(body)

# load swagger config 
app = connexion.App(__name__, specification_dir='configs/')

@app.app.before_request
def before_request():
    if request.url.startswith('http://'):
        url = request.url.replace('http://', 'https://', 1)
        code = 301
        return redirect(url, code=code)

@app.route('/', methods=['GET'])
def api_root():
    return redirect('/api/ui')

# SSL configuration
certificate_path = get_resources_path()
context = (os.path.normpath(f'{certificate_path}/articonf1.crt'), os.path.normpath(f'{certificate_path}/articonf1.key')) # certificate and key files

if is_running_locally():
    print("Running locally...")
    app.add_api(swagger_util.get_bundled_specs(Path("configs/swagger_local.yml")),
                resolver = connexion.RestyResolver("cms_rest_api"))
else:
    app.add_api(swagger_util.get_bundled_specs(Path("configs/swagger.yml")),
                resolver = connexion.RestyResolver("cms_rest_api"))

# start app
if __name__ == '__main__':
    message_handler = MessageHandler(Repository(), ReconnectingMessageManager.getInstance(), RestFetcher())
    message_manager = ReconnectingMessageManager.getInstance()
    message_manager.start_consuming('inhub', 'direct', 'trace-retrieval', True, message_received_callback)
    
    app.run(host='0.0.0.0', port=5000, debug=True, use_reloader=False, ssl_context=context) # disable reloader so only subscribed once to rabbitmq
