from typing import Tuple

from utils.logger import child

log = child("monitor")


def get_monitor_rect(index: int) -> Tuple[int, int, int, int]:
    """Return (x, y, width, height) for monitor at `index` (0-based).

    Falls back to the primary monitor if `index` is out of range.
    """
    try:
        from screeninfo import get_monitors
        monitors = get_monitors()
    except Exception as e:
        log.warning(f"screeninfo unavailable: {e}; defaulting to (0,0,1920,1080)")
        return (0, 0, 1920, 1080)
    if not monitors:
        return (0, 0, 1920, 1080)
    if index < 0 or index >= len(monitors):
        log.warning(f"monitor index {index} out of range (have {len(monitors)}); using primary")
        m = monitors[0]
    else:
        m = monitors[index]
    return (m.x, m.y, m.width, m.height)


def place_window(driver, monitor_index: int, window_size: Tuple[int, int]) -> None:
    x, y, w, h = get_monitor_rect(monitor_index)
    ww, wh = window_size
    # Centre window on target monitor
    wx = x + max(0, (w - ww) // 2)
    wy = y + max(0, (h - wh) // 2)
    try:
        driver.set_window_rect(wx, wy, ww, wh)
        log.info(f"placed window on monitor {monitor_index} at ({wx},{wy}) size ({ww},{wh})")
    except Exception:
        try:
            driver.set_window_position(wx, wy)
            driver.set_window_size(ww, wh)
            log.info(f"placed window (fallback) at ({wx},{wy}) size ({ww},{wh})")
        except Exception as e:
            log.warning(f"could not position window: {e}")
