import os
import cv2
import numpy as np


def imread(path, flags=cv2.IMREAD_UNCHANGED):
    """
    Unicode-safe image read (supports Chinese paths on Windows)
    """
    if not isinstance(path, str):
        raise TypeError("[imread] path must be str")

    if not os.path.exists(path):
        raise FileNotFoundError(f"[imread] file not exists: {path}")

    data = np.fromfile(path, dtype=np.uint8)
    img = cv2.imdecode(data, flags)

    if img is None:
        raise RuntimeError(f"[imread] cv2.imdecode failed: {path}")

    return img


def imwrite(path, img):
    """
    Unicode-safe image write
    """
    if img is None:
        raise ValueError("[imwrite] img is None")

    ext = os.path.splitext(path)[1].lower()
    if ext == "":
        raise ValueError("[imwrite] file extension is required")

    success, buf = cv2.imencode(ext, img)
    if not success:
        raise RuntimeError(f"[imwrite] cv2.imencode failed: {path}")

    buf.tofile(path)

def imshow(img,win_name='test',win_type=cv2.WINDOW_NORMAL,wait_key=0):
    cv2.namedWindow(win_name,flags=win_type)
    cv2.imshow(win_name,img)
    cv2.waitKey(wait_key)
