# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2026)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import annotations

import os
import platform
import re
import sys

SYSTEM = platform.system().lower()  # ty: ignore[unresolved-attribute]
IS_WINDOWS = SYSTEM == "windows"
IS_DARWIN = SYSTEM == "darwin"
IS_LINUX_OR_BSD = (SYSTEM == "linux") or ("bsd" in SYSTEM)


def _is_wsl() -> bool:
    """Return whether Streamlit is running inside Windows Subsystem for Linux."""
    if not IS_LINUX_OR_BSD:
        return False

    if "WSL_DISTRO_NAME" in os.environ or "WSL_INTEROP" in os.environ:
        return True

    try:
        with open("/proc/version", encoding="utf-8") as proc_version:
            version_info = proc_version.read().lower()
    except OSError:
        return False

    # "microsoft" matches the official WSL1 and WSL2 kernel strings, while
    # "wsl2" additionally covers custom WSL2 kernels. We avoid a bare "wsl"
    # substring check to prevent false positives from unrelated kernel build
    # strings (e.g. a build host that happens to contain "wsl").
    return "microsoft" in version_info or "wsl2" in version_info


IS_WSL = _is_wsl()


def is_pex() -> bool:
    """Return if streamlit running in pex.

    Pex modifies sys.path so the pex file is the first path and that's
    how we determine we're running in the pex file.
    """
    return bool(re.match(r".*pex$", sys.path[0]))


def is_repl() -> bool:
    """Return True if running in the Python REPL."""
    import inspect

    root_frame = inspect.stack()[-1]
    filename = root_frame[1]  # 1 is the filename field in this tuple.

    if filename.endswith(os.path.join("bin", "ipython")):
        return True

    # <stdin> is what the basic Python REPL calls the root frame's
    # filename, and <string> is what iPython sometimes calls it.
    return filename in {"<stdin>", "<string>"}


def is_executable_in_path(name: str) -> bool:
    """Check if executable is in OS path."""
    from shutil import which

    return which(name) is not None
