# add modules folder to interpreter path
import sys
import os
modules_path = '../../../modules/'
if os.path.exists(modules_path):
    sys.path.insert(1, modules_path)

### init logging ###
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 pathlib import Path
from env_info import is_running_locally, get_resources_path
from flask import request
from flask import redirect
from flask_cors import CORS

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

@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__':    
    app.run(host='0.0.0.0', port=5000, ssl_context=context) 
