"""Erkennt Spiele/Fokus-Fenster und kommentiert laut."""

from __future__ import annotations

import ctypes
import random
import re

GAME_HINTS = re.compile(
    r"(steam|game|spiel|valorant|minecraft|fortnite|league|csgo|counter-strike|"
    r"roblox|genshin|overwatch|dota|epic|battle\.net|unity|unreal|xbox|playstation|"
    r"launcher|gog|origin|ubisoft|rockstar|nintendo|emulator|retroarch|"
    r"warzone|apex|pubg|rocket league|elden ring|cyberpunk|hogwarts|"
    r"diablo|starcraft|hearthstone|world of warcraft|wow\b|palworld|"
    r"helldivers|lies of p|baldur|skyrim|fallout|witcher|dark souls|"
    r"borderlands|destiny|halo|forza|fifa|ea sports|nba 2k|"
    r"dead by daylight|among us|terraria|stardew|sims \d|"
    r"\- epic games|\- steam|\- gog)",
    re.I,
)


def foreground_title() -> str:
    try:
        user32 = ctypes.windll.user32
        hwnd = user32.GetForegroundWindow()
        length = user32.GetWindowTextLengthW(hwnd) + 1
        buf = ctypes.create_unicode_buffer(length)
        user32.GetWindowTextW(hwnd, buf, length)
        return buf.value or ""
    except Exception:
        return ""


def looks_like_gaming(title: str) -> bool:
    if not title or len(title) < 3:
        return False
    if "jam" in title.lower() and "python" in title.lower():
        return False
    return bool(GAME_HINTS.search(title))


def should_comment(
    session_idle_sec: float,
    stage: int,
    *,
    just_started: bool = False,
    last_spoken_at: float = 0.0,
) -> bool:
    """Wann Jam laut zum Zocken meckert."""
    import time

    from jam.speech import MIN_LINE_GAP_SEC

    if stage < 1:
        return False
    if time.time() - last_spoken_at < MIN_LINE_GAP_SEC:
        return False
    if just_started:
        return random.random() < 0.35
    if session_idle_sec < 25:
        return random.random() < 0.08
    chance = 0.12 if stage >= 2 else 0.08
    return random.random() < chance
