from django.db import connection
from pygments import highlight
from pygments.formatters import TerminalFormatter
from pygments.lexers import SqlLexer
from sqlparse import format
from django.conf import settings
from decimal import Decimal


def new_middleware(get_response):
    def middleware(request):
        response = get_response(request)
        print("===============================================")
        print("                [SQL Queries]")
        print("===============================================")

        if settings.DEBUG:
            num_queries = len(connection.queries)
            check_duplicates = set()
            total_execution_time = Decimal()

            for query in connection.queries:
                total_execution_time += Decimal(query["time"])
                check_duplicates.add(query["sql"])
                sqlformatted = format(
                    str((query["sql"])), reindent=True, keyword_case="upper"
                )
                print(highlight(sqlformatted, SqlLexer(), TerminalFormatter()))

        print("===============================================")
        print("                 [SQL Stats]")
        print("===============================================")
        print(f"Total queries: {num_queries}")
        print(f"Total execution time: {total_execution_time}ms")
        print(f"Duplicate queries: {num_queries - len(check_duplicates)}")
        print("===============================================")

        return response

    return middleware

