################################################################################
# Authors: Zemin Xu
# License: MIT, see LICENSE.md
################################################################################
"""Modify from e3nn"""

import itertools
import collections
from typing import List, Union, Callable


import torch
from e3nn.math import perm


from ._ictd import ICTD


class Irrep(tuple):
    r"""Irreducible representation of :math:`O(3)`

    This class does not contain any data, it is a structure that describe the representation.
    It is typically used as argument of other classes of the library to define the input and output representations of
    functions.

    Parameters
    ----------
    l : int
        non-negative integer, the degree of the representation, :math:`l = 0, 1, \dots`

    p : {1, -1}
        the parity of the representation

    Examples
    --------
    Create a scalar representation (:math:`l=0`) of even parity.

    >>> Irrep(0, 1)
    0e

    Create a pseudotensor representation (:math:`l=2`) of odd parity.

    >>> Irrep(2, -1)
    2o

    Create a vector representation (:math:`l=1`) of the parity of the cartesian harmonics (:math:`-1^l` gives odd parity).

    >>> Irrep("1y")
    1o

    >>> Irrep("2o").dim
    5

    >>> Irrep("2e") in Irrep("1o") * Irrep("1o")
    True

    >>> Irrep("1o") + Irrep("2o")
    1x1o+1x2o
    """

    def __new__(cls, l: Union[int, "Irrep", str, tuple], p=None):
        if p is None:
            if isinstance(l, Irrep):
                return l

            if isinstance(l, _MulIr):
                return l.ir.l

            if isinstance(l, str):
                try:
                    name = l.strip()
                    l = int(name[:-1])
                    assert l >= 0
                    p = {
                        "e": 1,
                        "o": -1,
                        "y": (-1) ** l,
                    }[name[-1]]
                except Exception:
                    raise ValueError(f'unable to convert string "{name}" into an Irrep')
            elif isinstance(l, tuple):
                l, p = l

        if not isinstance(l, int) or l < 0:
            raise ValueError(f"l must be positive integer, got {l}")
        if p not in (-1, 1):
            raise ValueError(f"parity must be on of (-1, 1), got {p}")
        return super().__new__(cls, (l, p))

    @property
    def l(self) -> int:  # noqa: E743
        r"""The degree of the representation, :math:`l = 0, 1, \dots`."""
        return self[0]

    @property
    def p(self) -> int:
        r"""The parity of the representation, :math:`p = \pm 1`."""
        return self[1]

    def __repr__(self) -> str:
        p = {+1: "e", -1: "o"}[self.p]
        return f"{self.l}{p}"

    @classmethod
    def iterator(cls, lmax=None):
        r"""Iterator through all the irreps of :math:`O(3)`

        Examples
        --------
        >>> it = Irrep.iterator()
        >>> next(it), next(it), next(it), next(it)
        (0e, 0o, 1o, 1e)
        """
        for l in itertools.count():
            yield Irrep(l, (-1) ** l)
            yield Irrep(l, -((-1) ** l))

            if l == lmax:
                break

    @property
    def dim(self) -> int:
        """The dimension of the cartesian representation, :math:`3 ** self.l`."""
        return int(3 ** self.l)

    @property
    def sdim(self) -> int:
        return 2 * self.l + 1
    
    @property
    def cdim(self) -> int:
        return int(3 ** self.l)
        
    @property
    def D(self) -> torch.Tensor:
        _, DS, _, _ = ICTD(self.l, self.l, decomposition=True)
        return DS[0]
    
    @property
    def C(self) -> torch.Tensor:
        _, _, CS, _ = ICTD(self.l, self.l, decomposition=False)
        return CS[0]

    @property
    def S(self) -> torch.Tensor:
        _, _, _, SS = ICTD(self.l, self.l, decomposition=False)
        return SS[0]

    def is_scalar(self) -> bool:
        """Equivalent to ``l == 0 and p == 1``"""
        return self.l == 0 and self.p == 1

    def __mul__(self, other):
        r"""Generate the irreps from the product of two irreps.

        Returns
        -------
        generator of `cartnn.o3.Irrep`
        """
        other = Irrep(other)
        p = self.p * other.p
        lmin = abs(self.l - other.l)
        lmax = self.l + other.l
        for l in range(lmin, lmax + 1):
            yield Irrep(l, p)

    def count(self, _value):
        raise NotImplementedError

    def index(self, _value):
        raise NotImplementedError

    def __rmul__(self, other):
        r"""
        >>> 3 * Irrep('1e')
        3x1e
        """
        assert isinstance(other, int)
        return Irreps([(other, self)])

    def __add__(self, other):
        return Irreps(self) + Irreps(other)

    def __contains__(self, _object):
        raise NotImplementedError

    def __len__(self):
        raise NotImplementedError


class _MulIr(tuple):
    def __new__(cls, mul, ir=None):
        if ir is None:
            mul, ir = mul

        assert isinstance(mul, int)
        assert isinstance(ir, Irrep)
        return super().__new__(cls, (mul, ir))

    @property
    def mul(self) -> int:
        return self[0]

    @property
    def ir(self) -> Irrep:
        return self[1]

    @property
    def dim(self) -> int:
        return self.mul * self.ir.dim

    @property
    def sdim(self) -> int:
        return self.mul * self.ir.sdim
    
    @property
    def cdim(self) -> int:
        return self.mul * self.ir.cdim
        
    def __repr__(self) -> str:
        return f"{self.mul}x{self.ir}"

    def __getitem__(self, item) -> Union[int, Irrep]:  # pylint: disable=useless-super-delegation
        return super().__getitem__(item)

    def count(self, _value):
        raise NotImplementedError

    def index(self, _value):
        raise NotImplementedError


class Irreps(tuple):
    r"""Direct sum of irreducible representations of :math:`O(3)`

    This class does not contain any data, it is a structure that describe the representation.
    It is typically used as argument of other classes of the library to define the input and output representations of
    functions.

    Attributes
    ----------
    dim : int
        the total dimension of the representation

    num_irreps : int
        number of irreps. the sum of the multiplicities

    ls : list of int
        list of :math:`l` values

    lmax : int
        maximum :math:`l` value

    Examples
    --------
    Create a representation of 100 :math:`l=0` of even parity and 50 pseudo-vectors.

    >>> x = Irreps([(100, (0, 1)), (50, (1, 1))])
    >>> x
    100x0e+50x1e

    >>> x.dim
    250

    Create a representation of 100 :math:`l=0` of even parity and 50 pseudo-vectors.

    >>> Irreps("100x0e + 50x1e")
    100x0e+50x1e

    >>> Irreps("100x0e + 50x1e + 0x2e")
    100x0e+50x1e+0x2e

    >>> Irreps("100x0e + 50x1e + 0x2e").lmax
    1

    >>> Irrep("2e") in Irreps("0e + 2e")
    True

    Empty Irreps

    >>> Irreps(), Irreps("")
    (, )
    """

    def __new__(cls, irreps=None) -> Union[_MulIr, "Irreps"]:
        if isinstance(irreps, Irreps):
            return super().__new__(cls, irreps)

        out = []
        if isinstance(irreps, Irrep):
            out.append(_MulIr(1, Irrep(irreps)))
        elif isinstance(irreps, str):
            try:
                if irreps.strip() != "":
                    for mul_ir in irreps.split("+"):
                        if "x" in mul_ir:
                            mul, ir = mul_ir.split("x")
                            mul = int(mul)
                            ir = Irrep(ir)
                        else:
                            mul = 1
                            ir = Irrep(mul_ir)

                        assert isinstance(mul, int) and mul >= 0
                        out.append(_MulIr(mul, ir))
            except Exception:
                raise ValueError(f'Unable to convert string "{irreps}" into an Irreps')
        elif irreps is None:
            pass
        else:
            for mul_ir in irreps:
                mul = None
                ir = None

                if isinstance(mul_ir, str):
                    mul = 1
                    ir = Irrep(mul_ir)
                elif isinstance(mul_ir, Irrep):
                    mul = 1
                    ir = mul_ir
                elif isinstance(mul_ir, _MulIr):
                    mul, ir = mul_ir
                elif len(mul_ir) == 2:
                    mul, ir = mul_ir
                    ir = Irrep(ir)

                if not (isinstance(mul, int) and mul >= 0 and ir is not None):
                    raise ValueError(f'Unable to interpret "{mul_ir}" as an irrep.')

                out.append(_MulIr(mul, ir))
        return super().__new__(cls, out)

    @staticmethod
    def cartesian_harmonics(lmax: int, p: int = -1) -> "Irreps":
        r"""representation of the cartesian_harmonics

        Parameters
        ----------
        lmax : int
            maximum :math:`l`

        p : {1, -1}
            the parity of the representation

        Returns
        -------
        `cartnn.o3.Irreps`
            representation of :math:`(Y^0, Y^1, \dots, Y^{\mathrm{lmax}})`

        Examples
        --------

        >>> Irreps.cartesian_harmonics(3)
        1x0e+1x1o+1x2e+1x3o

        >>> Irreps.cartesian_harmonics(4, p=1)
        1x0e+1x1e+1x2e+1x3e+1x4e
        """
        return Irreps([(1, (l, p**l)) for l in range(lmax + 1)])

    @staticmethod
    def spherical_harmonics(lmax: int, p: int = -1) -> "Irreps":
        r"""representation of the spherical harmonics

        Parameters
        ----------
        lmax : int
            maximum :math:`l`

        p : {1, -1}
            the parity of the representation

        Returns
        -------
        `cartnn.o3.Irreps`
            representation of :math:`(Y^0, Y^1, \dots, Y^{\mathrm{lmax}})`

        Examples
        --------

        >>> Irreps.spherical_harmonics(3)
        1x0e+1x1o+1x2e+1x3o

        >>> Irreps.spherical_harmonics(4, p=1)
        1x0e+1x1e+1x2e+1x3e+1x4e
        """
        return Irreps([(1, (l, p**l)) for l in range(lmax + 1)])
    
    def slices(self, cartesian: bool = True):
        r"""List of slices corresponding to indices for each irrep.

        Examples
        --------

        >>> Irreps('2x0e + 1e').slices()
        [slice(0, 2, None), slice(2, 5, None)]
        """
        s = []
        i = 0
        for mul_ir in self:
            if cartesian:
                s.append(slice(i, i + mul_ir.dim))
                i += mul_ir.dim
            else:
                s.append(slice(i, i + mul_ir.sdim))
                i += mul_ir.sdim
        return s
        
    def slices_by_ir(self, cartesian: bool = True):
        s = []
        i = 0
        for _, ir in self:
            if cartesian:
                s.append(slice(i, i + ir.dim))
                i += ir.dim
            else:
                s.append(slice(i, i + ir.sdim))
                i += ir.sdim
        return s
       
    def randn(
        self, *size: int, normalization: str = "component", requires_grad: bool = False, dtype=None, device=None
    ) -> torch.Tensor:
        r"""Random irreducible Cartesian tensor, which converted from e3nn spherical tensor.

        Parameters
        ----------
        *size : list of int
            size of the output tensor, needs to contains a ``-1``

        normalization : {'component', 'norm'}

        Returns
        -------
        `torch.Tensor`
            tensor of shape ``size`` where ``-1`` is replaced by ``self.dim``

        Examples
        --------

        >>> Irreps("5x0e + 10x1o").randn(5, -1, 5, normalization='norm').shape
        torch.Size([5, 35, 5])
        """
        
        di = size.index(-1)
        lsize = size[:di]
        rsize = size[di + 1 :]

        xs: list[torch.Tensor] = []
        if normalization == "component":
            x = torch.randn(*lsize, self.sdim, *rsize, requires_grad=requires_grad, dtype=dtype, device=device)
            with torch.no_grad():
                for s, (mul, ir) in zip(self.slices(False), self):
                    S = ir.S.to(dtype, device)
                    r = x.narrow(di, s.start, mul * ir.sdim)
                    r = r.view(*lsize, mul, ir.sdim, *rsize)
                    r = torch.tensordot(r, S, dims=([di+1], [0]))
                    r = r.view(*lsize, mul*ir.dim, *rsize)
                    xs.append(r)
            return torch.cat(xs, dim=di)
        elif normalization == "norm":
            with torch.no_grad():
                for s, (mul, ir) in zip(self.slices(False), self):
                    S = ir.S.to(dtype, device)
                    r = torch.randn(*lsize, mul, ir.sdim, *rsize, dtype=dtype, device=device)
                    r.div_(r.norm(2, dim=di + 1, keepdim=True))
                    r = torch.tensordot(r, S, dims=([di+1], [0]))
                    r = r.view(*lsize, mul*ir.dim, *rsize)
                    xs.append(r)
            return torch.cat(xs, dim=di)
        else:
            raise ValueError("Normalization needs to be 'norm' or 'component'")
        
        
    def __getitem__(self, i) -> Union[_MulIr, "Irreps"]:
        x = super().__getitem__(i)
        if isinstance(i, slice):
            return Irreps(x)
        return x

    def __contains__(self, ir) -> bool:
        ir = Irrep(ir)
        return ir in (irrep for _, irrep in self)

    def count(self, ir) -> int:
        r"""Multiplicity of ``ir``.

        Parameters
        ----------
        ir : `cartnn.o3.Irrep`

        Returns
        -------
        `int`
            total multiplicity of ``ir``
        """
        ir = Irrep(ir)
        return sum(mul for mul, irrep in self if ir == irrep)

    def index(self, _object):
        raise NotImplementedError

    def __add__(self, irreps) -> "Irreps":
        irreps = Irreps(irreps)
        return Irreps(super().__add__(irreps))

    def __mul__(self, other) -> "Irreps":
        r"""
        >>> (Irreps('2x1e') * 3).simplify()
        6x1e
        """
        if isinstance(other, Irreps):
            raise NotImplementedError("Use o3.TensorProduct for this, see the documentation")
        return Irreps(super().__mul__(other))

    def __rmul__(self, other) -> "Irreps":
        r"""
        >>> 2 * Irreps('0e + 1e')
        1x0e+1x1e+1x0e+1x1e
        """
        return Irreps(super().__rmul__(other))

    def simplify(self) -> "Irreps":
        """Simplify the representations.

        Returns
        -------
        `cartnn.o3.Irreps`

        Examples
        --------

        Note that simplify does not sort the representations.

        >>> Irreps("1e + 1e + 0e").simplify()
        2x1e+1x0e

        Equivalent representations which are separated from each other are not combined.

        >>> Irreps("1e + 1e + 0e + 1e").simplify()
        2x1e+1x0e+1x1e
        """
        out = []
        for mul, ir in self:
            if out and out[-1][1] == ir:
                out[-1] = (out[-1][0] + mul, ir)
            elif mul > 0:
                out.append((mul, ir))
        return Irreps(out)

    def remove_zero_multiplicities(self) -> "Irreps":
        """Remove any irreps with multiplicities of zero.

        Returns
        -------
        `cartnn.o3.Irreps`

        Examples
        --------

        >>> Irreps("4x0e + 0x1o + 2x3e").remove_zero_multiplicities()
        4x0e+2x3e

        """
        out = [(mul, ir) for mul, ir in self if mul > 0]
        return Irreps(out)

    def sort(self):
        r"""Sort the representations.

        Returns
        -------
        irreps : `cartnn.o3.Irreps`
        p : tuple of int
        inv : tuple of int

        Examples
        --------

        >>> Irreps("1e + 0e + 1e").sort().irreps
        1x0e+1x1e+1x1e

        >>> Irreps("2o + 1e + 0e + 1e").sort().p
        (3, 1, 0, 2)

        >>> Irreps("2o + 1e + 0e + 1e").sort().inv
        (2, 1, 3, 0)
        """
        Ret = collections.namedtuple("sort", ["irreps", "p", "inv"])
        out = [(ir, i, mul) for i, (mul, ir) in enumerate(self)]
        out = sorted(out)
        inv = tuple(i for _, i, _ in out)
        p = perm.inverse(inv)
        irreps = Irreps([(mul, ir) for ir, _, mul in out])
        return Ret(irreps, p, inv)

    def regroup(self) -> "Irreps":
        r"""Regroup the same irreps together.

        Equivalent to :meth:`sort` followed by :meth:`simplify`.

        Returns
        -------
            irreps: `cartnn.o3.Irreps`

        Examples
        --------

        >>> Irreps("1e + 0e + 1e + 0x2e").regroup()
        1x0e+2x1e
        """
        return self.sort().irreps.simplify()

    def filter(
        self,
        keep: Union["Irreps", List[Irrep], Callable[[_MulIr], bool]] = None,
        *,
        drop: Union["Irreps", List[Irrep], Callable[[_MulIr], bool]] = None,
        lmax: int = None,
    ) -> "Irreps":
        r"""Filter the irreps.

        Args:
            keep (`Irreps` or list of `Irrep` or function): list of irrep to keep
            drop (`Irreps` or list of `Irrep` or function): list of irrep to drop
            lmax (int): maximum :math:`l` value

        Returns:
            `Irreps`: filtered irreps

        Examples:
            >>> Irreps("1e + 2e + 0e").filter(keep=["0e", "1e"])
            1x1e+1x0e

            >>> Irreps("1e + 2e + 0e").filter(keep="2e + 2x1e")
            1x1e+1x2e

            >>> Irreps("1e + 2e + 0e").filter(drop="2e + 2x1e")
            1x0e

            >>> Irreps("1e + 2e + 0e").filter(lmax=1)
            1x1e+1x0e
        """
        if keep is None and drop is None and lmax is None:
            return self
        if keep is not None and drop is not None:
            raise ValueError("Cannot specify both keep and drop")
        if keep is not None and lmax is not None:
            raise ValueError("Cannot specify both keep and lmax")
        if drop is not None and lmax is not None:
            raise ValueError("Cannot specify both drop and lmax")

        if keep is not None:
            if isinstance(keep, str):
                keep = Irreps(keep)
            if isinstance(keep, Irrep):
                keep = [keep]
            if isinstance(keep, _MulIr):
                keep = [keep.ir]
            if callable(keep):
                return Irreps([mul_ir for mul_ir in self if keep(mul_ir)])
            keep = {Irrep(ir) for ir in keep}
            return Irreps([(mul, ir) for mul, ir in self if ir in keep])

        if drop is not None:
            if isinstance(drop, str):
                drop = Irreps(drop)
            if isinstance(drop, Irrep):
                drop = [drop]
            if isinstance(drop, _MulIr):
                drop = [drop.ir]
            if callable(drop):
                return Irreps([mul_ir for mul_ir in self if not drop(mul_ir)])
            drop = {Irrep(ir) for ir in drop}
            return Irreps([(mul, ir) for mul, ir in self if ir not in drop])

        if lmax is not None:
            return Irreps([(mul, ir) for mul, ir in self if ir.l <= lmax])

    @property
    def slice_by_mul(self):
        r"""Return the slice with respect to the multiplicities.
        """
        return _MulIndexSliceHelper(self)

    @property
    def dim(self) -> int:
        return sum(mul * ir.dim for mul, ir in self)

    @property
    def sdim(self) -> int:
        return sum(mul * ir.sdim for mul, ir in self)
    
    @property
    def cdim(self) -> int:
        return sum(mul * ir.cdim for mul, ir in self)
    
    @property
    def num_irreps(self) -> int:
        return sum(mul for mul, _ in self)

    @property
    def ls(self) -> List[int]:
        return [l for mul, (l, p) in self for _ in range(mul)]

    @property
    def lmax(self) -> int:
        if len(self) == 0:
            raise ValueError("Cannot get lmax of empty Irreps")
        return max(self.ls)

    @property
    def lmin(self) -> int:
        if len(self) == 0:
            raise ValueError("Cannot get lmin of empty Irreps")
        return min(self.ls)
    
    def __repr__(self) -> str:
        return "+".join(f"{mul_ir}" for mul_ir in self)
    
    def to_highest_weight(self, x: torch.Tensor):
        xis: list[torch.Tensor] = []
        for s, mul, ir in zip(self.slices(), self):
            xi = x[s].view(mul, ir.dim)
            xi = xi @ ir.C
            xis.append(xi)
        return torch.cat(xis, dim=-1)

class _MulIndexSliceHelper:
    irreps: Irreps

    def __init__(self, irreps) -> None:
        self.irreps = irreps

    def __getitem__(self, index: slice) -> Irreps:
        if not isinstance(index, slice):
            raise IndexError("Irreps.slice_by_mul only supports slices.")

        start, stop, stride = index.indices(self.irreps.num_irreps)
        if stride != 1:
            raise NotImplementedError("Irreps.slice_by_mul does not support strides.")

        out = []
        i = 0
        for mul, ir in self.irreps:
            if start <= i and i + mul <= stop:
                out.append((mul, ir))
            elif start < i + mul and i < stop:
                out.append((min(stop, i + mul) - max(start, i), ir))
            i += mul
        return Irreps(out)

