import sys
import logging

from app.core.config import settings

from app.constants import CONTEXT_SIZE, UNKNOWN_IDX, ALPHABET

char_to_index = {char: idx for idx, char in enumerate(ALPHABET)}


def setup_logger():
    logger = logging.getLogger()
    
    verbosity = settings.VERBOSITY
    level_map = {
        "DEBUG": logging.DEBUG,
        "INFO": logging.INFO,
        "WARNING": logging.WARNING,
        "ERROR": logging.ERROR,
        "CRITICAL": logging.CRITICAL,
    }
    log_level = level_map.get(verbosity)

    logger.setLevel(log_level)

    handler = logging.StreamHandler(sys.stdout)
    handler.setLevel(log_level)

    formatter = logging.Formatter("[%(levelname)s] - %(name)s:%(lineno)d - %(message)s")
    handler.setFormatter(formatter)

    logger.addHandler(handler)


if sys.platform == "win32":
    import win32con
    import win32gui
    import win32api
    import win32process

    def make_window_non_activating(win):
        hwnd = int(win.winId())

        ex_style = win32gui.GetWindowLong(hwnd, win32con.GWL_EXSTYLE)

        # Add styles
        ex_style |= win32con.WS_EX_NOACTIVATE
        ex_style |= win32con.WS_EX_TOPMOST
        ex_style |= win32con.WS_EX_TOOLWINDOW  # optional: hide from Alt+Tab

        win32gui.SetWindowLong(hwnd, win32con.GWL_EXSTYLE, ex_style)

        # Force update
        win32gui.SetWindowPos(
            hwnd, win32con.HWND_TOPMOST,
            0, 0, 0, 0,
            win32con.SWP_NOMOVE | win32con.SWP_NOSIZE | win32con.SWP_NOACTIVATE
        )


def tokenize(text: str) -> list[int]:
    """Convert last CONTEXT_SIZE chars to integer indices."""
    text = text.lower()[-CONTEXT_SIZE:]  # trim to context length
    padded = [' '] * (CONTEXT_SIZE - len(text)) + list(text)
    return [
        char_to_index.get(c, UNKNOWN_IDX)
        for c in padded
    ]
