from __future__ import annotations

import ctypes
import os
import subprocess
from typing import Any

DISABLE_ALERTS_ENV = "CLEAN_GG_RSS_DISABLE_ALERTS"


def hidden_subprocess_kwargs() -> dict[str, Any]:
    if os.name != "nt":
        return {}

    startupinfo = subprocess.STARTUPINFO()
    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    startupinfo.wShowWindow = getattr(subprocess, "SW_HIDE", 0)

    return {
        "startupinfo": startupinfo,
        "creationflags": getattr(subprocess, "CREATE_NO_WINDOW", 0),
    }


def run_hidden(command: list[str], **kwargs: Any) -> subprocess.CompletedProcess:
    merged_kwargs = hidden_subprocess_kwargs()
    merged_kwargs.update(kwargs)
    return subprocess.run(command, **merged_kwargs)


def show_error_dialog(title: str, message: str) -> bool:
    if os.name != "nt" or os.environ.get(DISABLE_ALERTS_ENV) == "1":
        return False

    flags = 0x00000010 | 0x00010000
    try:
        ctypes.windll.user32.MessageBoxW(None, message, title, flags)
    except Exception:
        return False
    return True
