import pathlib
from typing import Optional

import numpy as np


def process(
        img: np.ndarray, ratio: Optional[list[float]] = None) -> np.ndarray:
    if len(img.shape) != 3:
        return (img ** ratio[0]).astype(img.dtype)
    ratio = ratio or [1., 1., 1.]
    img_ret = img.copy()
    for i in range(img.shape[-1]):
        img_ret[:, :, i] = img[:, :, i] * ratio[i]
    return img_ret


def switch_channels(img: np.ndarray, channels: list[int] = None) -> np.ndarray:
    """
    重新排列图像的通道顺序，例如：
    switch_channels(img, [2,1,0]) 可将 BGR 转为 RGB
    """
    if img.ndim != 3:
        raise ValueError("img must be a 3-dimensional array (H, W, C)")
    channels = channels or [2, 1, 0]
    if len(channels) != img.shape[2]:
        raise ValueError("channels length must match the number of channels in img")
    if max(channels) >= img.shape[2] or min(channels) < 0:
        raise ValueError(f"channels indices must be between 0 and {img.shape[2] - 1}")
    return img[:, :, channels]


def rgb_read(path: str | pathlib.Path):
    import cv2
    return switch_channels(cv2.imread(str(path)))


def rgb_write(img: np.ndarray, path: str | pathlib.Path):
    import cv2
    cv2.imwrite(str(path), switch_channels(img))
