# -*- coding: utf-8 -*-
"""No network call of the addon waits forever (docs/plan/skin-optimization/020-tv-handover.md, W7).

`requests` has no default timeout: a call without one hangs as long as a dead server keeps the connection, and many
older calls (TMDbClient, the Webshare API, UI.py) were written without one. `install()` gives every requests call that
names no timeout DEFAULT_TIMEOUT. It costs nothing until something imports requests (the widget fast path never does):
the patch waits for `requests.sessions` to load.
"""
import importlib.util
import sys

DEFAULT_TIMEOUT = (6, 30)            # connect, read (seconds between two received bytes, not the whole answer)


def _patch(module):
    session = module.Session
    if getattr(session.request, 'milionar_timeout', False):
        return
    original = session.request

    def request(self, method, url, **kwargs):
        if kwargs.get('timeout') is None:
            kwargs['timeout'] = DEFAULT_TIMEOUT
        return original(self, method, url, **kwargs)
    request.milionar_timeout = True
    session.request = request


class _Finder(object):
    """Patches requests.sessions right after it loads."""
    milionar_timeout = True          # one finder per interpreter, also when main.py reloads this module

    def find_spec(self, name, path=None, target=None):
        if name != 'requests.sessions':
            return None
        sys.meta_path.remove(self)
        try:
            spec = importlib.util.find_spec(name)
        finally:
            sys.meta_path.insert(0, self)
        if spec is None or spec.loader is None or not hasattr(spec.loader, 'exec_module'):
            return spec
        original = spec.loader.exec_module

        def exec_module(module):
            original(module)
            _patch(module)
        spec.loader.exec_module = exec_module
        return spec


_SECRET = None


def redact(text):
    """Keys never reach kodi.log (account plan, security): `api_key=…`, `wst=…`, `token=…`, `Bearer …`."""
    global _SECRET
    if _SECRET is None:
        import re
        _SECRET = re.compile(r'((?:api_key|apikey|wst|token|key|password|pass)=)[^&\s\'"]+|(Bearer\s+)[A-Za-z0-9._~+/=-]+', re.I)
    return _SECRET.sub(lambda m: (m.group(1) or m.group(2)) + '…', text)


def _redact_log():
    """Every xbmc.log of this interpreter goes through redact() (once per interpreter)."""
    try:
        import xbmc
        if getattr(xbmc.log, 'milionar_redact', False):
            return
        original = xbmc.log

        def log(msg, level=xbmc.LOGDEBUG):
            try:
                msg = redact(msg if isinstance(msg, str) else str(msg))
            except Exception:
                pass
            return original(msg, level)
        log.milionar_redact = True
        xbmc.log = log
    except Exception:
        pass


def install():
    _redact_log()
    try:
        if 'requests.sessions' in sys.modules:
            _patch(sys.modules['requests.sessions'])
        elif not any(getattr(finder, 'milionar_timeout', False) for finder in sys.meta_path):
            sys.meta_path.insert(0, _Finder())
    except Exception:                 # never in the way of the addon
        pass
