"""Muravey launcher — .pyw extension = no console window on Windows."""
import os
import sys

# Set working directory to script location
os.chdir(os.path.dirname(os.path.abspath(__file__)))

# Redirect stdout/stderr to devnull (pythonw has no console)
if sys.stdout is None:
    sys.stdout = open(os.devnull, "w")
if sys.stderr is None:
    sys.stderr = open(os.devnull, "w")
try:
    sys.stdout.write("")
except Exception:
    sys.stdout = open(os.devnull, "w")
try:
    sys.stderr.write("")
except Exception:
    sys.stderr = open(os.devnull, "w")

# Auto-elevate to admin (required for CSCA)
if sys.platform == "win32":
    import ctypes
    if not ctypes.windll.shell32.IsUserAnAdmin():
        # Re-launch self as admin, no console
        script = os.path.abspath(__file__)
        pythonw = sys.executable  # pythonw.exe
        ctypes.windll.shell32.ShellExecuteW(None, "runas", pythonw, f'"{script}"', None, 0)
        sys.exit(0)

# Force UTF-8 encoding everywhere
os.environ["PYTHONIOENCODING"] = "utf-8"
if hasattr(sys.stdout, "reconfigure"):
    try:
        sys.stdout.reconfigure(encoding="utf-8", errors="replace")
    except Exception:
        pass
if hasattr(sys.stderr, "reconfigure"):
    try:
        sys.stderr.reconfigure(encoding="utf-8", errors="replace")
    except Exception:
        pass

# Add CUDA to PATH
cuda_path = r"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.0\bin\x64"
if os.path.isdir(cuda_path):
    os.environ["PATH"] = cuda_path + ";" + os.environ.get("PATH", "")

# Run launch — .pyd (compiled) or .py (source)
# Nuitka names .pyd as launch.cp311-win_amd64.pyd — rename to launch.pyd for import
import glob as _glob
_pyd_files = _glob.glob("launch*.pyd")
if _pyd_files and not os.path.exists("launch.pyd"):
    try:
        os.rename(_pyd_files[0], "launch.pyd")
    except Exception:
        pass

if os.path.exists("launch.pyd"):
    import launch
    launch._guard()
    launch._pre_configure()
    from pathlib import Path as _P
    if not (_P(__file__).parent / ("\x2e" + "\x64\x65\x76")).is_file():
        launch._check_token()
    launch._launch()
elif os.path.exists("launch.py"):
    # Source version — run as script
    import runpy
    runpy.run_path("launch.py", run_name="__main__")
else:
    # Try import anyway (launch might be in sys.path)
    try:
        import launch
        launch._guard()
        launch._pre_configure()
        launch._check_token()
        launch._launch()
    except Exception as e:
        try:
            import ctypes
            ctypes.windll.user32.MessageBoxW(0, f"Cannot find launch module: {e}", "Muravey Error", 0x10)
        except:
            pass
