"""The estimators and their intervals (see DESIGN.md, Methods)."""
import numpy as np
from scipy.optimize import nnls

from .sim import LAUNCH, POST, REGION

PRE_WIN = slice(LAUNCH - POST, LAUNCH)
POST_WIN = slice(LAUNCH, LAUNCH + POST)
FULL_PRE = slice(0, LAUNCH)


def naive(trips, unit=0):
    return float(trips[unit, POST_WIN].mean() / trips[unit, PRE_WIN].mean() - 1.0)


def naive_interval(trips, rng, unit=0, n_boot=1000, level=0.90):
    pre = trips[unit, PRE_WIN]
    post = trips[unit, POST_WIN]
    bi = rng.integers(0, len(pre), (n_boot, len(pre)))
    ai = rng.integers(0, len(post), (n_boot, len(post)))
    boots = post[ai].mean(axis=1) / pre[bi].mean(axis=1) - 1.0
    lo, hi = np.quantile(boots, [(1 - level) / 2, 1 - (1 - level) / 2])
    return float(lo), float(hi)


def comparison_growth(trips, unit, pool):
    g_unit = trips[unit, POST_WIN].mean() / trips[unit, PRE_WIN].mean()
    g_pool = np.mean([trips[j, POST_WIN].mean() / trips[j, PRE_WIN].mean() for j in pool])
    return float(g_unit / g_pool - 1.0)


def did(trips, unit, pool):
    ly = np.log(trips)
    d_unit = ly[unit, POST_WIN].mean() - ly[unit, FULL_PRE].mean()
    d_pool = np.mean([ly[j, POST_WIN].mean() - ly[j, FULL_PRE].mean() for j in pool])
    return float(np.exp(d_unit - d_pool) - 1.0)


def pretrend_slope(trips, unit, pool):
    """Slope per year of the log gap between the unit and the pool average over the last 52 weeks before launch."""
    ly = np.log(trips)
    weeks = np.arange(LAUNCH - 52, LAUNCH)
    gap = ly[unit, weeks] - ly[pool][:, weeks].mean(axis=0)
    return float(np.polyfit(weeks / 52.0, gap, 1)[0])


def _design(t):
    cols = [np.ones_like(t), t / 52.0]
    for k in (1, 2, 3):
        cols += [np.sin(2 * np.pi * k * t / 52), np.cos(2 * np.pi * k * t / 52)]
    return np.column_stack(cols)


def forecast_path(series, fit_end, horizon=POST):
    t_fit = np.arange(fit_end, dtype=float)
    t_new = np.arange(fit_end, fit_end + horizon, dtype=float)
    beta, *_ = np.linalg.lstsq(_design(t_fit), np.log(series[:fit_end]), rcond=None)
    return np.exp(_design(t_new) @ beta)


def forecast(trips, unit=0, fit_end=LAUNCH):
    pred = forecast_path(trips[unit], fit_end)
    actual = trips[unit, fit_end:fit_end + POST]
    return float(actual.sum() / pred.sum() - 1.0)


BACKTEST_STARTS = tuple(range(78, 105, 2))


def forecast_backtest_errors(trips, unit=0):
    return [forecast(trips, unit, fit_end=f) for f in BACKTEST_STARTS]


def sc_weights(trips, unit, pool):
    if len(pool) == 0:
        raise ValueError("synthetic control needs at least one comparison city")
    ly = np.log(trips)
    a = ly[unit, FULL_PRE] - ly[unit, FULL_PRE].mean()
    B = ly[pool][:, FULL_PRE]
    B = (B - B.mean(axis=1, keepdims=True)).T
    big = 1000.0
    A_aug = np.vstack([B, big * np.ones((1, B.shape[1]))])
    b_aug = np.concatenate([a, [big]])
    w, _ = nnls(A_aug, b_aug, maxiter=5000)
    s = w.sum()
    return w / s if s > 0 else np.full(len(pool), 1.0 / len(pool))


def synthetic_control(trips, unit, pool, return_weights=False):
    ly = np.log(trips)
    w = sc_weights(trips, unit, pool)
    pool_dm = ly[pool] - ly[pool][:, FULL_PRE].mean(axis=1, keepdims=True)
    cf_log = ly[unit, FULL_PRE].mean() + w @ pool_dm
    cf = np.exp(cf_log)
    lift = float(trips[unit, POST_WIN].sum() / cf[POST_WIN].sum() - 1.0)
    if return_weights:
        return lift, w, cf
    return lift


def same_region_removed(pool, unit):
    return [j for j in pool if REGION[j] != REGION[unit]]


def sc_no_neighbours(trips, unit, pool):
    return synthetic_control(trips, unit, same_region_removed(pool, unit))


def placebo_estimates(method, trips, pool):
    """Run `method(trips, unit, pool)` on each city of the method's own pool as if it had launched, with the rest of
    that pool as its comparisons (city 0 is never in a pool)."""
    out = []
    for j in pool:
        others = [c for c in pool if c != j]
        out.append(method(trips, j, others))
    return out


def placebo_interval(estimate, placebo, level=0.90):
    lo_q, hi_q = np.quantile(np.asarray(placebo), [(1 - level) / 2, 1 - (1 - level) / 2])
    return float(estimate - hi_q), float(estimate - lo_q)
