# add modules folder to interpreter path
import sys
import os
from pathlib import Path
from typing import Dict, Any

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

# load swagger config
import connexion
from security import swagger_util
from env_info import is_running_locally, get_resources_path
from flask import request
from flask import redirect

app = connexion.App(__name__, specification_dir='configs/')

from db.entities.layer_adapter import LayerAdapter

@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, debug=False, ssl_context=context)
