from flask import Response, request
from lewy_globals import colors as c
from markupsafe import escape
import json
import lewy_globals
import lewy_api_v1
import requests
import time
import traceback

def api_greeting():
	string = {'status': 200, 'msg': f"ok (lewangoalski {lewy_globals.version})", 'latest_api': f"v{lewy_globals.apiVersion}"}
	string = json.dumps(string)
	return Response(string, mimetype='application/json')

def api_global_catchall(received_request):
	lewy_globals.apiRequests += 1
	if request.environ['REMOTE_ADDR'] != "127.0.0.1" or (lewy_globals.isProxied and request.environ['X-Forwarded-For'] != "127.0.0.1"):
			lewy_globals.outsideApiHits += 1

	request_list = received_request.split('/')
	api_version = request_list[0]
	if request_list[0] == 'v1':
		# use v1 api
		del request_list[0]
		# if list is empty, aka /api/v1/, or /api/v1
		if request_list == [''] or request_list == []:
			resp = api_greeting()
		try:
			status, received, data = lewy_api_v1.lookup(request_list, request)
		except Exception as e:
			lewy_globals.apiFailedRequests += 1
			stripped_filename = __file__[max(__file__.rfind("/"), __file__.rfind("\\")) + 1:]
			print(f"\n{c.FAIL}Error! /api/{received_request} -> {stripped_filename}:L{e.__traceback__.tb_lineno} -> {type(e).__name__}{c.ENDC}:")
			print(traceback.format_exc())
			status, received, data = 500, f"internal server error: call ended in failure: {e} ({stripped_filename}:L{e.__traceback__.tb_lineno})", []
		resp = Response(json.dumps({'status': status, 'msg': received, 'data': data}), mimetype='application/json', status=status)
	else:
		lewy_globals.apiFailedRequests += 1
		status, received, data = 405, f'error: unsupported api version: "{request_list[0]}". try: "v{lewy_globals.apiVersion}".', []
		resp = Response(json.dumps({'status': status, 'msg': received, 'data': data}), mimetype='application/json', status=status)

	return resp