import os
import ctypes
from .utils import hex_to_rgb

def enable_windows_ansi():
    """Enable ANSI escape sequences on Windows 10+ terminals."""
    if os.name == 'nt':
        kernel32 = ctypes.windll.kernel32
        handle = kernel32.GetStdHandle(-11)  # STD_OUTPUT_HANDLE = -11
        mode = ctypes.c_uint32()
        if kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
            new_mode = mode.value | 0x0004  # ENABLE_VIRTUAL_TERMINAL_PROCESSING
            kernel32.SetConsoleMode(handle, new_mode)

# Enable ANSI processing on Windows at import time
enable_windows_ansi()

def color_text(text: str, hex_color: str, background=False) -> str:
    """Return ANSI-colored text from a hex code."""
    r, g, b = hex_to_rgb(hex_color)
    code_type = 48 if background else 38  # background or foreground
    return f"\033[{code_type};2;{r};{g};{b}m{text}\033[0m"

def bold(text: str) -> str:
    """Return bold ANSI styled text."""
    return f"\033[1m{text}\033[0m"

def underline(text: str) -> str:
    """Return underlined ANSI styled text."""
    return f"\033[4m{text}\033[0m"
