import numpy as np
from microscope.nodes import BinaryMask, Float, Image, Node


class MeanDarkMask(Node):
    id = "example.lab.mean_dark_mask"
    version = 1
    name = "Mean dark-pixel mask"
    category = "Tissue demonstration"
    description = "Marks RGB pixels whose channel mean is below a configurable cutoff."

    inputs = {"image": Image}
    outputs = {"mask": BinaryMask}
    parameters = {
        "threshold": Float(
            160,
            min=0,
            max=255,
            label="Mean intensity cutoff",
            description="Pixels at or below this 8-bit mean are marked foreground.",
        )
    }

    def run(self, image, threshold):
        if image.ndim != 3 or image.shape[2] != 3:
            raise ValueError("Expected an RGB image with three channels")
        mean_intensity = image.astype(np.float32).mean(axis=2)
        return {"mask": (mean_intensity <= threshold).astype(np.uint8)}
