"""Conditional logit and panel mixed logit, written out in numpy so every step can be read and tested.

Shapes: X is (situations, alternatives, attributes); y is the chosen alternative per situation; person maps each situation
to a respondent 0..P-1. Rows must be grouped by person (see `sort_by_person`).
"""
import numpy as np
from scipy import optimize, stats
from scipy.special import logsumexp


def sort_by_person(X, y, person):
    order = np.argsort(person, kind="stable")
    return X[order], y[order], person[order]


# ---------------------------------------------------------------- conditional logit

def clogit_loglik(beta, X, y):
    V = X @ beta
    return float(np.sum(V[np.arange(len(y)), y] - logsumexp(V, axis=1)))


def clogit_probs(beta, X):
    V = X @ beta
    V -= V.max(axis=1, keepdims=True)
    P = np.exp(V)
    return P / P.sum(axis=1, keepdims=True)


def fit_clogit(X, y, tol=1e-10, max_iter=100):
    """Newton-Raphson on the exact gradient and Hessian. Returns estimates, covariance (inverse Hessian), log-likelihood."""
    K = X.shape[2]
    beta = np.zeros(K)
    idx = np.arange(len(y))
    for it in range(max_iter):
        P = clogit_probs(beta, X)
        xbar = np.einsum("tj,tjk->tk", P, X)
        grad = (X[idx, y] - xbar).sum(axis=0)
        D = X - xbar[:, None, :]
        H = -np.einsum("tj,tjk,tjl->kl", P, D, D)
        step = np.linalg.solve(H, grad)
        beta = beta - step
        if np.max(np.abs(step)) < tol:
            break
    else:
        raise RuntimeError("conditional logit did not converge")
    P = clogit_probs(beta, X)
    xbar = np.einsum("tj,tjk->tk", P, X)
    D = X - xbar[:, None, :]
    H = -np.einsum("tj,tjk,tjl->kl", P, D, D)
    grad = (X[idx, y] - xbar).sum(axis=0)
    return {"beta": beta, "cov": np.linalg.inv(-H), "loglik": clogit_loglik(beta, X, y),
            "iterations": it + 1, "max_abs_gradient": float(np.max(np.abs(grad)))}


# ---------------------------------------------------------------- draws

def halton_normal(n_people, n_draws, dims, seed):
    """Scrambled Halton points mapped to standard normals, n_draws consecutive points per person: (people, draws, dims)."""
    u = stats.qmc.Halton(d=dims, scramble=True, seed=seed).random(n_people * n_draws)
    u = np.clip(u, 1e-12, 1 - 1e-12)
    return stats.norm.ppf(u).reshape(n_people, n_draws, dims)


# ---------------------------------------------------------------- panel mixed logit

class MixedLogit:
    """Panel mixed logit. `random` maps attribute index -> 'n' (normal) or 'ln' (log-normal); other attributes are fixed.

    Parameters, in order: the fixed coefficients, then the mean of each random coefficient, then its standard deviation
    (for 'ln', the mean and sd of the coefficient's log). A person's coefficients are held across their choices.
    """

    def __init__(self, X, y, person, random, draws, block=48):
        self.X, self.y, self.person = X, y, person
        if np.any(np.diff(person) < 0):
            raise ValueError("rows must be grouped by person")
        self.K = X.shape[2]
        self.rand_idx = sorted(random)
        self.dist = [random[k] for k in self.rand_idx]
        self.fixed_idx = [k for k in range(self.K) if k not in random]
        self.Z = draws  # (people, R, len(random))
        self.P = int(person.max()) + 1
        if draws.shape[0] != self.P or draws.shape[2] != len(self.rand_idx):
            raise ValueError("draws must be (people, R, number of random coefficients)")
        self.R = draws.shape[1]
        starts = np.searchsorted(person, np.arange(self.P))
        ends = np.append(starts[1:], len(person))
        self.blocks = [(p0, min(p0 + block, self.P), starts[p0], ends[min(p0 + block, self.P) - 1])
                       for p0 in range(0, self.P, block)]
        # Offsets of each person's first row inside its block, for reduceat sums over a person's choices.
        self.offsets = [starts[p0:p1] - t0 for p0, p1, t0, _ in self.blocks]
        self.XT = np.ascontiguousarray(X.transpose(0, 2, 1))  # (T, K, J)
        self.n_params = len(self.fixed_idx) + 2 * len(self.rand_idx)

    def names(self, attrs):
        return ([attrs[k] for k in self.fixed_idx] + [attrs[k] for k in self.rand_idx]
                + [f"sd.{attrs[k]}" for k in self.rand_idx])

    def _split(self, theta):
        nf, nr = len(self.fixed_idx), len(self.rand_idx)
        return theta[:nf], theta[nf:nf + nr], theta[nf + nr:]

    def _coefs(self, theta, p0, p1):
        """Coefficients per person and draw (p, R, K), plus d(beta)/d(mu) and d(beta)/d(sd) for the random ones."""
        bf, mu, sd = self._split(theta)
        Z = self.Z[p0:p1]
        B = np.empty((p1 - p0, self.R, self.K))
        B[:, :, self.fixed_idx] = bf
        dmu = np.empty((p1 - p0, self.R, len(self.rand_idx)))
        for i, (k, d) in enumerate(zip(self.rand_idx, self.dist)):
            lin = mu[i] + sd[i] * Z[:, :, i]
            if d == "n":
                B[:, :, k] = lin
                dmu[:, :, i] = 1.0
            elif d == "ln":
                B[:, :, k] = np.exp(lin)
                dmu[:, :, i] = B[:, :, k]
            else:
                raise ValueError(d)
        return B, dmu, dmu * Z

    def _block(self, theta, b, want_grad):
        p0, p1, t0, t1 = b
        X, y = self.X[t0:t1], self.y[t0:t1]
        loc = self.person[t0:t1] - p0
        off = self.offsets[self.blocks.index(b)]
        B, dmu, dsd = self._coefs(theta, p0, p1)
        Bt = B[loc]  # (T, R, K)
        V = np.matmul(Bt, self.XT[t0:t1])  # (T, R, J)
        lse = logsumexp(V, axis=2)
        T = len(y)
        logp = V[np.arange(T), :, y] - lse  # (T, R)
        logS = np.add.reduceat(logp, off, axis=0)  # (p, R): log of the product over a person's choices
        ll_p = logsumexp(logS, axis=1) - np.log(self.R)
        if not want_grad:
            return ll_p, None
        Pj = np.exp(V - lse[:, :, None])
        G = X[np.arange(T), y][:, None, :] - np.matmul(Pj, X)  # (T, R, K)
        Gp = np.add.reduceat(G, off, axis=0)
        w = np.exp(logS - logsumexp(logS, axis=1, keepdims=True))  # (p, R)
        g_f = np.einsum("pr,prk->pk", w, Gp[:, :, self.fixed_idx])
        Gr = Gp[:, :, self.rand_idx]
        g_mu = np.einsum("pr,prk->pk", w, Gr * dmu)
        g_sd = np.einsum("pr,prk->pk", w, Gr * dsd)
        return ll_p, np.concatenate([g_f, g_mu, g_sd], axis=1)

    def loglik_people(self, theta):
        return np.concatenate([self._block(theta, b, False)[0] for b in self.blocks])

    def loglik(self, theta):
        return float(self.loglik_people(theta).sum())

    def loglik_grad(self, theta):
        ll, g = 0.0, np.zeros(self.n_params)
        for b in self.blocks:
            lp, gp = self._block(theta, b, True)
            ll += lp.sum()
            g += gp.sum(axis=0)
        return ll, g

    def scores(self, theta):
        """Per-person gradient of the log-likelihood, (people, parameters); its outer product gives the BHHH covariance."""
        return np.concatenate([self._block(theta, b, True)[1] for b in self.blocks])

    def fit(self, start, gtol=1e-6, max_iter=2000):
        res = optimize.minimize(lambda t: tuple(-v for v in self.loglik_grad(t)), np.asarray(start, float), jac=True,
                                method="BFGS", options={"gtol": gtol, "maxiter": max_iter})
        theta = res.x
        H = self.hessian(theta)
        cov = np.linalg.inv(-H)
        ll, g = self.loglik_grad(theta)
        return {"theta": theta, "cov": cov, "loglik": ll, "iterations": int(res.nit), "converged": bool(res.success),
                "message": str(res.message), "max_abs_gradient": float(np.max(np.abs(g)))}

    def hessian(self, theta, rel_step=1e-5):
        n = len(theta)
        H = np.zeros((n, n))
        for i in range(n):
            h = rel_step * max(1.0, abs(theta[i]))
            e = np.zeros(n)
            e[i] = h
            H[:, i] = (self.loglik_grad(theta + e)[1] - self.loglik_grad(theta - e)[1]) / (2 * h)
        return (H + H.T) / 2

    def choice_probs(self, theta):
        """Population-level probability of each alternative in each situation (averaged over draws), (T, J)."""
        out = []
        for p0, p1, t0, t1 in self.blocks:
            loc = self.person[t0:t1] - p0
            B, _, _ = self._coefs(theta, p0, p1)
            V = np.matmul(B[loc], self.XT[t0:t1])
            Pj = np.exp(V - logsumexp(V, axis=2)[:, :, None])
            out.append(Pj.mean(axis=1))
        return np.concatenate(out)
