"""Opt-in request-local measurements. Never record arguments or exceptions.

Times are inclusive (parents and children must not be added). This is neither
a package cache nor a source of authorization. Diagnostic failures are ignored.
"""
from contextlib import contextmanager, ExitStack
from contextvars import ContextVar
from functools import wraps
from time import perf_counter, process_time
import os
import threading

_record = ContextVar('export_performance', default=None)
_locks = ContextVar('export_performance_locks', default=())


@contextmanager
def capture():
    result = {'schema': 1, 'stages': {}, 'counts': {}, 'inclusive': True}
    token = _record.set(result)
    try:
        wall, cpu = perf_counter(), process_time()
    except Exception:
        wall = cpu = None
    try:
        yield result
    finally:
        try:
            result.update(total_seconds=perf_counter()-wall, cpu_seconds=process_time()-cpu)
        except Exception:
            result.update(total_seconds=None, cpu_seconds=None, timing_error=True)
        _record.reset(token)


def count(name, amount=1):
    record = _record.get()
    if record is not None:
        try:
            record['counts'][name] = record['counts'].get(name, 0) + amount
        except Exception:
            try:
                record['timing_error'] = True
            except Exception:
                pass


@contextmanager
def stage(name):
    record = _record.get()
    if record is None:
        yield
        return
    try:
        wall, cpu = perf_counter(), process_time()
    except Exception:
        yield
        return
    complete = False
    try:
        yield
        complete = True
    finally:
        try:
            entry = record['stages'].setdefault(name, {'calls': 0, 'seconds': 0., 'cpu_seconds': 0., 'incomplete': 0})
            entry['calls'] += 1
            entry['seconds'] += perf_counter()-wall
            entry['cpu_seconds'] += process_time()-cpu
            entry['incomplete'] += int(not complete)
        except Exception:
            try:
                record['timing_error'] = True
            except Exception:
                pass


def measured(name):
    def decorate(function):
        @wraps(function)
        def call(*args, **kwargs):
            with stage(name):
                return function(*args, **kwargs)
        return call
    return decorate


@contextmanager
def lock_context(manager, name):
    key = (os.getpid(), threading.get_ident(), name)
    held = _locks.get()
    if key in held:
        # Measure actual ownership, not inclusive duplicate reentrant holds.
        with manager:
            yield
        return
    with ExitStack() as stack:
        with stage(name + '.wait'):
            stack.enter_context(manager)
        token = _locks.set(held + (key,))
        try:
            with stage(name + '.held'):
                yield
        finally:
            _locks.reset(token)
