"""macOS idle detection — AC power, user activity, thermal state."""

from __future__ import annotations

import re
import subprocess

import structlog

logger = structlog.get_logger()


def is_on_ac_power() -> bool:
    """Check if Mac is plugged in to AC power."""
    try:
        result = subprocess.run(["pmset", "-g", "batt"], capture_output=True, text=True, timeout=5)
        return "AC Power" in result.stdout
    except Exception:
        logger.warning("Failed to check power state, assuming battery")
        return False


def get_user_idle_seconds() -> float:
    """Get seconds since last user input (keyboard/mouse/trackpad)."""
    try:
        result = subprocess.run(["ioreg", "-c", "IOHIDSystem"], capture_output=True, text=True, timeout=5)
        match = re.search(r'"HIDIdleTime"\s*=\s*(\d+)', result.stdout)
        if match:
            return int(match.group(1)) / 1e9  # nanoseconds -> seconds
    except Exception:
        logger.warning("Failed to check idle time")
    return 0


def is_user_idle(minutes: int = 5) -> bool:
    """Check if user has been idle for at least N minutes."""
    return get_user_idle_seconds() >= (minutes * 60)


def is_thermal_throttling() -> bool:
    """Check if CPU is being thermally throttled."""
    try:
        result = subprocess.run(["pmset", "-g", "therm"], capture_output=True, text=True, timeout=5)
        if "CPU_Speed_Limit" in result.stdout:
            match = re.search(r"CPU_Speed_Limit\s*=\s*(\d+)", result.stdout)
            if match:
                return int(match.group(1)) < 100
    except Exception:
        logger.warning("Failed to check thermal state")
    return False


def should_run(min_idle_minutes: int = 5, require_ac: bool = True, check_thermal: bool = True) -> bool:
    """Check all conditions for whether the worker should process jobs."""
    if require_ac and not is_on_ac_power():
        return False
    if not is_user_idle(min_idle_minutes):
        return False
    if check_thermal and is_thermal_throttling():
        return False
    return True


def get_hardware_info() -> dict:
    """Get Apple Silicon hardware info."""
    info = {}
    try:
        result = subprocess.run(["sysctl", "-n", "machdep.cpu.brand_string"], capture_output=True, text=True, timeout=5)
        info["chip"] = result.stdout.strip()
    except Exception:
        pass
    try:
        result = subprocess.run(["sysctl", "-n", "hw.memsize"], capture_output=True, text=True, timeout=5)
        info["memory_gb"] = int(result.stdout.strip()) // (1024**3)
    except Exception:
        pass
    return info
