"""
www.ubugtrack.com - Crash Reporter for Python, version 1 (Python 3.8 and later)
Sends the uncaught exceptions of a Python app (scripts, threads, WSGI and ASGI
web apps) to the Crash Reporter of a uBugtrack project. No dependency.

    import ubugtrack_crashreport
    ubugtrack_crashreport.init_crash_reporter('YOUR_CRASH_KEY', 'YOUR_APP_VERSION')

Web apps: add the middleware too, so the errors of the requests are reported
with their URL (the framework still answers its 500 as before):
    Flask:     app.wsgi_app = UbugtrackWSGIMiddleware(app.wsgi_app)
    Django:    application = UbugtrackWSGIMiddleware(get_wsgi_application())
    FastAPI, Starlette:  app.add_middleware(UbugtrackASGIMiddleware)
    Other ASGI apps:     app = UbugtrackASGIMiddleware(app)

Python still prints the tracebacks as before: they are only reported.
KeyboardInterrupt and SystemExit are never reported. The same error is sent
once per minute (30 reports per minute at most), a report waits 3 seconds at
most, and the reporter never raises nor prints anything.

Report something by hand, e.g. an exception you caught:
    ubugtrack_crashreport.report_exception()      # inside "except"
    ubugtrack_crashreport.send_error('Title', 'Details')
"""

import atexit
import contextvars
import os
import platform
import sys
import threading
import time
import traceback
import urllib.error
import urllib.parse
import urllib.request

__all__ = ['init_crash_reporter', 'report_exception', 'send_error',
           'UbugtrackWSGIMiddleware', 'UbugtrackASGIMiddleware']

_ENDPOINT = 'https://ubugtrack.com/crashdump.php'
_TIMEOUT = 3
# The same error is sent once per minute, and 30 reports per minute at most
_SAME_ERROR_DELAY = 60
_MAX_PER_MINUTE = 30
# The server keeps the first 2047 bytes of a log
_LOG_MAX = 2047
_HEADER = 'Traceback (most recent call last):\n'
_STDLIB = os.path.dirname(os.__file__).replace('\\', '/') + '/'

_key = ''
_version = 'unknown'
_endpoint = _ENDPOINT
_command = 'python'
_installed = False
_previous_excepthook = None
_previous_thread_excepthook = None
_hooked_frameworks = set()

_lock = threading.Lock()
_last_sent = {}
_minute_start = None
_minute_count = 0
_pending = set()

# The request being answered, set by the middlewares: "GET /cart/7"
_request = contextvars.ContextVar('ubugtrack_request', default=None)


#*****************************************************************
# PUBLIC API

def init_crash_reporter(crash_key, version=None, endpoint=None):
    """
    Call it once, when the app starts.
    endpoint: only to send to another uBugtrack server (tests).
    """
    global _key, _version, _endpoint, _command, _installed
    global _previous_excepthook, _previous_thread_excepthook

    _key = str(crash_key or '')
    # The server drops a crash without version; it keeps 64 characters
    _version = str(version or '').strip()[:64] or 'unknown'
    if endpoint:
        _endpoint = str(endpoint)
    _command = _script()

    with _lock:
        if _installed:
            return
        _installed = True
    _previous_excepthook = sys.excepthook
    sys.excepthook = _excepthook
    _previous_thread_excepthook = threading.excepthook
    threading.excepthook = _thread_excepthook
    atexit.register(_wait_pending)


def report_exception(exc=None, query=None):
    """
    Reports an exception you caught yourself (by default, the one being handled).
    query: the request that failed, e.g. "GET /cart/7", instead of the current one.
    """
    if exc is None:
        exc = sys.exc_info()[1]
    _report(exc, query=query)


def send_error(title, details):
    """
    Reports anything: a title (grouped by title in uBugtrack) and the details.
    """
    try:
        _send(str(title), _context(None) + '\n\n' + str(details), wait=False)
    except Exception:
        pass


class UbugtrackWSGIMiddleware:
    """
    Reports the errors of the requests of a WSGI app, then raises them again.
    """

    def __init__(self, app):
        self.app = app
        _hook_frameworks()

    def __call__(self, environ, start_response):
        token = _request.set(_wsgi_query(environ))
        try:
            return self.app(environ, start_response)
        except Exception as exc:
            _report(exc)
            raise
        finally:
            _request.reset(token)


class UbugtrackASGIMiddleware:
    """
    Reports the errors of the requests of an ASGI app, then raises them again.
    """

    def __init__(self, app):
        self.app = app
        _hook_frameworks()

    async def __call__(self, scope, receive, send):
        # "lifespan" fails on purpose in the apps that do not support it
        if scope.get('type') not in ('http', 'websocket'):
            await self.app(scope, receive, send)
            return

        token = _request.set(_asgi_query(scope))
        try:
            await self.app(scope, receive, send)
        except Exception as exc:
            _report(exc)
            raise
        finally:
            _request.reset(token)


#*****************************************************************
# HOOKS

def _excepthook(exc_type, exc, tb):
    # Python prints the traceback first, then the process ends after the report
    try:
        (_previous_excepthook or sys.__excepthook__)(exc_type, exc, tb)
    finally:
        _report(exc, tb=tb, wait=True)


def _thread_excepthook(args):
    try:
        if _previous_thread_excepthook is not None:
            _previous_thread_excepthook(args)
    finally:
        _report(args.exc_value, tb=args.exc_traceback, wait=True)


def _hook_frameworks():
    # Flask and Django answer the 500 themselves: the error never reaches the
    # middleware, their got_request_exception signal reports it
    try:
        flask = sys.modules.get('flask')
        if flask is not None and 'flask' not in _hooked_frameworks:
            flask.got_request_exception.connect(_on_request_exception, weak=False)
            _hooked_frameworks.add('flask')
    except Exception:
        pass
    try:
        django = sys.modules.get('django.core.signals')
        if django is not None and 'django' not in _hooked_frameworks:
            django.got_request_exception.connect(_on_request_exception, weak=False,
                                                 dispatch_uid='ubugtrack_crashreport')
            _hooked_frameworks.add('django')
    except Exception:
        pass


def _on_request_exception(sender=None, **kwargs):
    # Flask gives the exception, Django sends it while handling it
    exc = kwargs.get('exception')
    if not isinstance(exc, BaseException):
        exc = sys.exc_info()[1]
    _report(exc)


#*****************************************************************
# REPORT

def _report(exc, tb=None, query=None, wait=False):
    try:
        if not isinstance(exc, BaseException) or isinstance(exc, (KeyboardInterrupt, SystemExit)):
            return
        # Reported by a middleware, then raised to the top: only once
        if getattr(exc, '_ubugtrack_reported', False):
            return
        try:
            exc._ubugtrack_reported = True
        except Exception:
            pass

        title = _title(exc)
        if not _key or not _can_send(title):
            return
        context = _context(query) + '\n\n'
        try:
            log = _traceback_text(exc, tb or exc.__traceback__, _LOG_MAX - _size(context))
        except Exception:
            log = title
        _post_later(title, context + log, wait)
    except Exception:
        pass


# "ZeroDivisionError: division by zero", "myshop.cart.CartError: ...": the last
# line of the traceback (first line of the message only)
def _title(exc):
    cls = type(exc)
    name = getattr(cls, '__qualname__', None) or cls.__name__
    module = getattr(cls, '__module__', None)
    if not isinstance(module, str):
        module = '<unknown>'
    if module not in ('__main__', 'builtins'):
        name = module + '.' + name
    try:
        message = str(exc)
    except Exception:
        message = '<exception str() failed>'
    message = message.strip().split('\n')[0].strip()
    return name + ': ' + message if message else name


# The page (web request) or the script (command line) that failed
def _context(query):
    if query is None:
        query = _request.get()
    if query:
        return 'Query: ' + _one_line(str(query))
    return 'Command: ' + _command


def _script():
    argv = getattr(sys, 'argv', None) or ['']
    script = argv[0] or ''
    # Interactive, "python -c" or "python -": no file
    if script in ('', '-c', '-'):
        return ('python ' + script).strip()
    return 'python ' + os.path.abspath(script)


def _wsgi_query(environ):
    try:
        path = environ.get('SCRIPT_NAME', '') + environ.get('PATH_INFO', '')
        try:
            # WSGI gives the bytes of the path as latin-1
            path = path.encode('latin-1').decode('utf-8')
        except UnicodeError:
            pass
        # No query string: it may hold tokens
        return str(environ.get('REQUEST_METHOD') or 'GET') + ' ' + (path or '/')
    except Exception:
        return None


def _asgi_query(scope):
    try:
        root = scope.get('root_path') or ''
        path = scope.get('path') or '/'
        if root and not path.startswith(root):
            path = root + path
        return str(scope.get('method') or 'WEBSOCKET') + ' ' + path
    except Exception:
        return None


def _one_line(text):
    return text.replace('\r', ' ').replace('\n', ' ')


def _size(text):
    return len(text.encode('utf-8', 'replace'))


def _is_lib(filename):
    path = filename.replace('\\', '/')
    return ('/site-packages/' in path or '/dist-packages/' in path
            or path.startswith(_STDLIB) or filename.startswith('<frozen'))


def _set_stacks(chain, stacks, removed=()):
    for item, frames in zip(chain, stacks):
        if not removed:
            item.stack = traceback.StackSummary.from_list(frames)
            continue
        # The number of frames left out, in their place
        items = []
        for frame in frames:
            if id(frame) not in removed:
                items.append(frame)
            elif items and isinstance(items[-1], int):
                items[-1] += 1
            else:
                items.append(1)
        item.stack = _Stack(items)


class _Stack(traceback.StackSummary):
    # Frames, and "  [3 frames left out]" where frames were left out
    def format(self, **kwargs):
        lines = []
        part = []
        for item in self + [0]:
            if isinstance(item, int):
                lines.extend(traceback.StackSummary.from_list(part).format(**kwargs))
                part = []
                if item:
                    lines.append('  [%d frame%s left out]\n' % (item, 's' if item > 1 else ''))
            else:
                part.append(item)
        return lines


# The traceback as Python prints it. When it is too long for the server, frames
# are left out (never the one that raised), so that the end is not cut.
def _traceback_text(exc, tb, budget):
    error = traceback.TracebackException(type(exc), exc, tb)

    # The exceptions printed, the oldest first
    chain = []
    item = error
    while item is not None and len(chain) < 100:
        chain.insert(0, item)
        if item.__cause__ is not None:
            item = item.__cause__
        elif not item.__suppress_context__:
            item = item.__context__
        else:
            item = None

    # The frames of the middlewares are noise
    stacks = [[frame for frame in item.stack if frame.filename != __file__] for item in chain]
    _set_stacks(chain, stacks)
    text = ''.join(error.format())
    if _size(text) <= budget:
        return text

    # Left out first: the frames of the libraries, then of the app; the oldest
    # exceptions and the outermost frames first
    _set_stacks(chain, [[] for item in chain])
    total = _size(''.join(error.format())) + len(_HEADER) * len(chain)
    sizes = {}
    candidates = []
    for age, frames in enumerate(stacks):
        for pos, frame in enumerate(frames):
            sizes[id(frame)] = _size(''.join(traceback.StackSummary.from_list([frame]).format()))
            total += sizes[id(frame)]
            if pos < len(frames) - 1:
                candidates.append((0 if _is_lib(frame.filename) else 1, age, pos, id(frame)))
    order = [candidate[3] for candidate in sorted(candidates)]
    count = 0
    while count < len(order) and total > budget:
        total -= sizes[order[count]]
        count += 1

    # Then exactly, with the "left out" lines
    while True:
        _set_stacks(chain, stacks, set(order[:count]))
        text = ''.join(error.format())
        if _size(text) <= budget or count >= len(order):
            break
        count += 1
    if _size(text) <= budget:
        return text
    # Still too long: the last exception only
    return ''.join(error.format(chain=False))


#*****************************************************************
# SENDING

def _can_send(title):
    global _minute_start, _minute_count
    now = time.monotonic()
    with _lock:
        last = _last_sent.get(title)
        if last is not None and now - last < _SAME_ERROR_DELAY:
            return False
        if _minute_start is None or now - _minute_start >= 60:
            _minute_start = now
            _minute_count = 0
        if _minute_count >= _MAX_PER_MINUTE:
            return False
        _minute_count += 1
        if len(_last_sent) >= 1000:
            _last_sent.clear()
        _last_sent[title] = now
        return True


def _send(title, log, wait):
    if _key and _can_send(title):
        _post_later(title, log, wait)


# In a thread, so that a request is not slowed down; wait: the process ends
def _post_later(title, log, wait):
    body = urllib.parse.urlencode({
        'project_key': _key,
        'manufacturer': 'Python',
        'model': platform.python_version(),
        'appversion': _version,
        'logtitle': title,
        'logfull': log,
    }, errors='replace').encode('ascii')

    thread = threading.Thread(target=_post, args=(_endpoint, body), name='ubugtrack-crashreport', daemon=True)
    if not wait:
        with _lock:
            _pending.add(thread)
    try:
        thread.start()
    except RuntimeError:
        # No new thread while Python shuts down
        with _lock:
            _pending.discard(thread)
        _post(_endpoint, body)
        return
    if wait:
        thread.join(_TIMEOUT)


def _post(endpoint, body):
    try:
        request = urllib.request.Request(endpoint, data=body, headers={
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'})
        with urllib.request.urlopen(request, timeout=_TIMEOUT) as answer:
            answer.read()
    except urllib.error.HTTPError as error:
        error.close()
    except Exception:
        pass
    finally:
        with _lock:
            _pending.discard(threading.current_thread())


# The reports still being sent when the script ends: 3 seconds at most
def _wait_pending():
    deadline = time.monotonic() + _TIMEOUT
    with _lock:
        threads = list(_pending)
    for thread in threads:
        remaining = deadline - time.monotonic()
        if remaining <= 0:
            break
        try:
            thread.join(remaining)
        except RuntimeError:
            pass
