"""In-memory cache of decoded dress images (and their average colour) so we never re-read PNGs on every frame."""
import os
import threading
from collections import OrderedDict

import cv2
import numpy as np

MAX_ITEMS = 32
_cache = OrderedDict()  # dress_id -> (file_path, mtime, bgra_array, mean_bgr)
_lock = threading.Lock()


def get_dress_image(dress_id, file_path):
    """Return (BGRA array, average BGR colour) for a dress; loads from disk only if needed/changed."""
    try:
        mtime = os.path.getmtime(file_path)
    except OSError:
        return None, None

    with _lock:
        hit = _cache.get(dress_id)
        if hit and hit[0] == file_path and hit[1] == mtime:
            _cache.move_to_end(dress_id)
            return hit[2], hit[3]

    img = cv2.imread(file_path, cv2.IMREAD_UNCHANGED)  # keeps the alpha channel
    if img is None:
        return None, None
    if img.ndim == 2:
        img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGRA)
    elif img.shape[2] == 3:
        img = cv2.cvtColor(img, cv2.COLOR_BGR2BGRA)
    img = np.ascontiguousarray(img)
    solid = img[:, :, 3] > 200
    mean_bgr = tuple(float(v) for v in img[solid][:, :3].mean(axis=0)) if solid.any() else None

    with _lock:
        _cache[dress_id] = (file_path, mtime, img, mean_bgr)
        _cache.move_to_end(dress_id)
        while len(_cache) > MAX_ITEMS:
            _cache.popitem(last=False)
    return img, mean_bgr
