import os
import logging
import socket

from rhodecode.config.constants import PYCHARM_DEBUG_PAUSE_AT_STARTUP

log = logging.getLogger(__name__)


class PyCharmDebugMiddleware:
    def __init__(self, handler):
        self.handler = handler
        self._start_debugger()

    def _start_debugger(self):
        try:
            import pydevd_pycharm

            suspend = os.getenv(PYCHARM_DEBUG_PAUSE_AT_STARTUP, "0") == "1"
            host = "host.docker.internal"  # assuming that app is running inside docker, and the debug server is on the same machine

            pydevd_pycharm.settrace(
                host,
                suspend=suspend,
                stdoutToServer=True,
                stderrToServer=True,
            )
            log.debug("PyCharm debugger attached successfully!")
        except ImportError:
            log.warning("pydevd_pycharm not installed. Debugging disabled.")
        except ConnectionRefusedError:
            ip = socket.gethostbyname(host)
            log.warning(f"debug server is not running on host[ip]: {host}[{ip}], shutdown remote debugger.")
            pydevd_pycharm.stoptrace()

    def __call__(self, environ, start_response):
        return self.handler(environ, start_response)
