# -*- coding: utf-8 -*-
"""
utils.py  –  Shared helpers for the REM plugin.
"""

import os
from qgis.core import QgsRasterLayer, QgsProject


def apply_rem_style(layer: QgsRasterLayer) -> None:
    """
    Apply the bundled REM colour ramp QML style to *layer* and refresh
    the canvas.  Safe to call even if the style file is missing.
    """
    style_path = os.path.join(
        os.path.dirname(__file__), "styles", "rem_style.qml"
    )
    if not os.path.exists(style_path):
        return

    msg, succeeded = layer.loadNamedStyle(style_path)
    if succeeded:
        layer.triggerRepaint()
    return succeeded


def check_projected_crs(layer) -> bool:
    """Return True if the layer has a projected (non-geographic) CRS."""
    return not layer.crs().isGeographic()


def metres_per_pixel(raster_layer) -> float:
    """Average pixel size in metres (assumes projected CRS)."""
    return (
        raster_layer.rasterUnitsPerPixelX()
        + raster_layer.rasterUnitsPerPixelY()
    ) / 2.0


def suggest_sample_interval(raster_layer) -> float:
    """
    Return a sensible default sample interval:
    5× the pixel size, rounded to the nearest 5 m.
    """
    mpp = metres_per_pixel(raster_layer)
    raw = mpp * 5
    return max(5.0, round(raw / 5) * 5)
