"""Detect connected monitors and resolve which one a window should target."""

from __future__ import annotations

import math
import re
from dataclasses import dataclass

from screeninfo import get_monitors


@dataclass(frozen=True)
class MonitorGeometry:
    display_id: int
    x: int
    y: int
    width: int
    height: int
    diagonal_in: float | None
    is_primary: bool


def _display_number(name: str) -> int | None:
    match = re.search(r"DISPLAY(\d+)", name, re.IGNORECASE)
    return int(match.group(1)) if match else None


def list_monitors() -> list[MonitorGeometry]:
    monitors = []
    for m in get_monitors():
        diagonal_in = None
        if m.width_mm and m.height_mm:
            diagonal_in = math.hypot(m.width_mm, m.height_mm) / 25.4
        monitors.append(MonitorGeometry(
            display_id=_display_number(m.name) or 0,
            x=m.x, y=m.y, width=m.width, height=m.height,
            diagonal_in=diagonal_in, is_primary=m.is_primary,
        ))
    return sorted(monitors, key=lambda mon: mon.display_id)


def get_monitor(display_id: int | None) -> MonitorGeometry:
    monitors = list_monitors()
    if not monitors:
        raise SystemExit("error: no monitors detected")
    if display_id is None:
        for mon in monitors:
            if mon.is_primary:
                return mon
        return monitors[0]
    for mon in monitors:
        if mon.display_id == display_id:
            return mon
    available = ", ".join(str(mon.display_id) for mon in monitors)
    raise SystemExit(f"error: --monitor {display_id} not found (available: {available})")


def format_monitor_list() -> str:
    lines = []
    for mon in list_monitors():
        tag = " (primary)" if mon.is_primary else ""
        diag = f'{mon.diagonal_in:.1f}"' if mon.diagonal_in else "unknown size"
        lines.append(f"  {mon.display_id}: {mon.width}x{mon.height} @ ({mon.x},{mon.y}) - {diag}{tag}")
    return "\n".join(lines)
