import os

import cv2


def ensure_dir(path):
    os.makedirs(path, exist_ok=True)


def dump_image(out_dir, filename, frame):
    full_path = os.path.join(out_dir, filename)
    folder = os.path.dirname(full_path)
    if folder:
        ensure_dir(folder)
    cv2.imwrite(full_path, frame)


def load_image(image_path):
    frame = cv2.imread(image_path)
    if frame is None:
        raise RuntimeError(f"Image not found: {image_path}")
    return frame


def resize_if_needed(frame, max_width):
    if max_width and frame.shape[1] > max_width:
        scale = max_width / float(frame.shape[1])
        new_w = int(frame.shape[1] * scale)
        new_h = int(frame.shape[0] * scale)
        return cv2.resize(frame, (new_w, new_h), interpolation=cv2.INTER_AREA)
    return frame


def to_grayscale(frame):
    return cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
