"""Convert a spectrum to a colour, using the CIE 1931 colour-matching functions.

The class ColourSystem converts a spectrum, or a chromaticity, to the rgb
values that display its colour in a colour system, and cs_srgb is the sRGB
colour system of computer screens and of colours in HTML and CSS. The
colour-matching functions are read from the file cie-cmf.txt, which must be in
the same folder as this module.
"""

from pathlib import Path

import numpy as np

# The CIE 1931 2-degree colour-matching functions, xbar, ybar and zbar (the
# columns of CMF), at the wavelengths CMF_LAM: 380 nm to 780 nm in 5 nm steps.
_table = np.loadtxt(Path(__file__).with_name("cie-cmf.txt"))
CMF_LAM, CMF = _table[:, 0], _table[:, 1:]


def xyz_from_xy(x, y):
    """Return the chromaticity (x, y, z), where z = 1 - x - y."""
    return np.array((x, y, 1 - x - y))


def srgb_encode(rgb):
    """Apply the sRGB transfer function ("gamma correction") to linear rgb
    values between 0 and 1."""
    rgb = np.clip(rgb, 0, 1)
    return np.where(rgb <= 0.0031308, 12.92 * rgb,
                    1.055 * rgb ** (1 / 2.4) - 0.055)


def spec_to_xyz(spec, lam=CMF_LAM):
    """Return the chromaticity (x, y, z) of light with the spectrum spec.

    spec is the spectral power at the wavelengths lam (nm, in increasing
    order), by default those of the colour-matching functions. These are
    interpolated linearly onto any other wavelengths, and taken to be zero
    outside their range.
    """
    cmf = np.column_stack([np.interp(lam, CMF_LAM, f, left=0, right=0)
                           for f in CMF.T])
    XYZ = np.trapezoid(np.asarray(spec)[:, np.newaxis] * cmf, lam, axis=0)
    total = XYZ.sum()
    return XYZ / total if total > 0 else XYZ


class ColourSystem:
    """A colour system, defined by the chromaticities of its red, green and
    blue primaries and of its white point, and by its transfer function."""

    def __init__(self, red, green, blue, white, encode):
        """red, green, blue and white are chromaticities (x, y, z), as given
        by xyz_from_xy; encode is a function that applies the system's
        transfer function to linear rgb values."""
        self.red, self.green, self.blue = red, green, blue
        self.white = white
        self.encode = encode
        # The columns of M are the chromaticities of the primaries. Scaling
        # them by s, so that r = g = b = 1 gives the white point, gives the
        # matrix that converts rgb to xyz; its inverse converts xyz to rgb.
        M = np.column_stack((red, green, blue))
        s = np.linalg.solve(M, white)
        self.xyz_to_rgb_matrix = np.linalg.inv(M * s)

    def xyz_to_rgb(self, xyz, out_fmt=None):
        """Return the rgb values that display the chromaticity xyz.

        A chromaticity outside the system's gamut is first desaturated: white
        is added until no component is negative. The rgb values are scaled so
        that the largest is 1, encoded by the system's transfer function, and
        returned as fractions between 0 and 1 or, if out_fmt is "html", as the
        HTML hex string "#rrggbb".
        """
        rgb = self.xyz_to_rgb_matrix @ xyz
        if rgb.min() < 0:
            # Outside the gamut: desaturate by adding white.
            rgb -= rgb.min()
        if rgb.max() > 0:
            rgb /= rgb.max()
        rgb = self.encode(rgb)
        if out_fmt == "html":
            return self.rgb_to_hex(rgb)
        return rgb

    @staticmethod
    def rgb_to_hex(rgb):
        """Return the HTML hex string "#rrggbb" for rgb values between 0
        and 1."""
        r, g, b = np.round(255 * np.asarray(rgb)).astype(int)
        return f"#{r:02x}{g:02x}{b:02x}"

    def spec_to_rgb(self, spec, lam=CMF_LAM, out_fmt=None):
        """Return the rgb values that display the colour of light with the
        spectrum spec, at the wavelengths lam (see spec_to_xyz)."""
        return self.xyz_to_rgb(spec_to_xyz(spec, lam), out_fmt)


# The sRGB colour system: the primaries of ITU-R BT.709, the standard for
# high-definition television, with the white point of the CIE standard
# illuminant D65.
illuminant_D65 = xyz_from_xy(0.3127, 0.3290)
cs_srgb = ColourSystem(red=xyz_from_xy(0.64, 0.33),
                       green=xyz_from_xy(0.30, 0.60),
                       blue=xyz_from_xy(0.15, 0.06),
                       white=illuminant_D65,
                       encode=srgb_encode)
