import os
import subprocess
import sys
import webbrowser

DEBUG = os.getenv("DEBUG", "").lower() == "true"


def open_url(url: str) -> bool:
    """
    Open a URL in a browser.
    webbrowser.open() does not work as expected on wsl so we only use webbrowser on windows and macos.

    Args:
        url: The URL to open.

    Returns:
        True if the URL was opened successfully, False otherwise.
    """
    if sys.platform in ("win32", "darwin"):
        try:
            return webbrowser.open(url, new=2)
        except Exception:
            return False

    # Linux / WSL helpers
    for cmd in (["xdg-open", url], ["gio", "open", url], ["gnome-open", url]):
        try:
            proc = subprocess.run(
                cmd,
                stdout=subprocess.DEVNULL,
                stderr=subprocess.PIPE if DEBUG else subprocess.DEVNULL,
                text=DEBUG,
                check=False,
            )

            if proc.returncode == 0:
                return True

            if DEBUG and proc.stderr:
                print(proc.stderr.rstrip())

        except FileNotFoundError:
            pass
        except Exception as e:
            if DEBUG:
                print(f"{cmd[0]} failed: {e}")

    return False
