"""Drivers, the revenue identity, the forecasting models and the plan-versus-actual bridge.

Revenue R is rider spend before tips: fares plus additional charges. Segments are solo and shared (the rider authorised
a shared trip). The identity, per month:

    R = T x sum_s w_s x (m_s x f_s + a_s)

T trips, w_s share of trips in segment s, m_s miles per trip, f_s fare per mile, a_s additional charges per trip.
Tips = tau x fares, with fares = T x sum_s w_s m_s f_s.
"""
from __future__ import annotations

import csv
import math
from pathlib import Path

import numpy as np
from scipy.optimize import minimize

ROOT = Path(__file__).resolve().parents[1]
MONTHLY = ROOT / "data" / "monthly.csv"
SEGMENTS = ("solo", "shared")
PERIOD = 12
MIN_SHARED_TRIPS = 1000
DRIVERS = ["T", "w_shared", "m_solo", "f_solo", "a_solo", "m_shared", "f_shared", "a_shared", "tau"]
DIRECT = ["R", "B"]
RAW_SCALE = {"w_shared"}  # modelled on its own scale and clipped to [0, 1]; all others on the log scale


# ---------------------------------------------------------------- data and identity

def load_monthly(path: Path = MONTHLY) -> dict:
    """Month -> segment -> totals, in month order."""
    out: dict = {}
    with path.open(encoding="utf-8", newline="") as fh:
        for r in csv.DictReader(fh):
            out.setdefault(r["month"], {})[r["segment"]] = {
                "trips": int(r["trips"]), "fares": float(r["fares"]), "tips": float(r["tips"]),
                "charges": float(r["additional_charges"]), "miles": float(r["miles"]),
                "trips_with_fare": int(r["trips_with_fare"]), "trips_pooled": int(r["trips_pooled"]),
            }
    return dict(sorted(out.items()))


def actual_drivers(seg: dict) -> dict:
    """The driver values of one month, from its segment totals. Undefined ratios (a segment with no trips) are None."""
    T = sum(seg[s]["trips"] for s in SEGMENTS)
    d: dict = {"T": float(T)}
    for s in SEGMENTS:
        t = seg[s]["trips"]
        d[f"w_{s}"] = t / T
        d[f"m_{s}"] = seg[s]["miles"] / t if t else None
        d[f"f_{s}"] = seg[s]["fares"] / seg[s]["miles"] if seg[s]["miles"] else None
        d[f"a_{s}"] = seg[s]["charges"] / t if t else None
    fares = sum(seg[s]["fares"] for s in SEGMENTS)
    d["tau"] = sum(seg[s]["tips"] for s in SEGMENTS) / fares
    return d


def revenue(seg: dict) -> float:
    return sum(seg[s]["fares"] + seg[s]["charges"] for s in SEGMENTS)


def tips(seg: dict) -> float:
    return sum(seg[s]["tips"] for s in SEGMENTS)


def compose(d: dict) -> tuple[float, float]:
    """Revenue and bookings (revenue plus tips) from driver values; a segment with share 0 contributes 0."""
    rev, fares = 0.0, 0.0
    for s in SEGMENTS:
        w = d[f"w_{s}"]
        if w == 0:
            continue
        rev += w * (d[f"m_{s}"] * d[f"f_{s}"] + d[f"a_{s}"])
        fares += w * d[f"m_{s}"] * d[f"f_{s}"]
    return d["T"] * rev, d["T"] * rev + d["tau"] * d["T"] * fares


def model_inputs(data: dict) -> dict:
    """Series to model, month-ordered. Shared ratios in months with fewer than MIN_SHARED_TRIPS shared trips carry
    forward the last month with at least that many (for modelling only; the identity uses the actuals)."""
    months = list(data)
    series = {k: [] for k in DRIVERS + DIRECT}
    last = {}
    for mo in months:
        seg = data[mo]
        d = actual_drivers(seg)
        for k in DRIVERS:
            v = d[k]
            if k.endswith("_shared") and k != "w_shared":
                if seg["shared"]["trips"] >= MIN_SHARED_TRIPS:
                    last[k] = v
                else:
                    v = last[k]
            series[k].append(v)
        series["R"].append(revenue(seg))
        series["B"].append(revenue(seg) + tips(seg))
    return {k: np.array(v, dtype=float) for k, v in series.items()}


# ---------------------------------------------------------------- ETS (additive Holt-Winters, period 12)

def _init(z: np.ndarray) -> tuple[float, np.ndarray]:
    first = z[:PERIOD]
    level = float(first.mean())
    return level, first - level


def _run(z: np.ndarray, params: np.ndarray, damped: bool, steps: int = 0):
    """One-step errors over z and the forecasts for the next `steps` periods (steps <= 12).

    S[t] is the seasonal state applied to month t: S[0..11] come from the first 12 months, and after month t is
    observed, S[t + 12] is updated from it."""
    if damped:
        alpha, beta, gamma, phi = params
    else:
        (alpha, gamma), beta, phi = params, 0.0, 0.0
    n = len(z)
    level, season0 = _init(z)
    S = np.empty(n + PERIOD)
    S[:PERIOD] = season0
    trend = 0.0
    errs = np.empty(n)
    for t in range(n):
        x = z[t]
        errs[t] = x - (level + phi * trend + S[t])
        new_level = alpha * (x - S[t]) + (1 - alpha) * (level + phi * trend)
        trend = beta * (new_level - level) + (1 - beta) * phi * trend
        level = new_level
        S[t + PERIOD] = gamma * (x - level) + (1 - gamma) * S[t]
    fc = np.array([level + sum(phi ** j for j in range(1, h + 1)) * trend + S[n + h - 1]
                   for h in range(1, steps + 1)])
    return errs, fc


BOUNDS = {False: [(0.01, 0.99), (0.0, 0.99)], True: [(0.01, 0.99), (0.0, 0.5), (0.0, 0.99), (0.8, 0.98)]}
STARTS = {False: [[0.3, 0.1], [0.7, 0.1], [0.3, 0.5]],
          True: [[0.3, 0.05, 0.1, 0.9], [0.7, 0.1, 0.1, 0.9], [0.3, 0.05, 0.5, 0.95]]}


def fit(z: np.ndarray, damped: bool) -> tuple[np.ndarray, float]:
    """Least squares on one-step errors, skipping the first 12 (they only fit the initial states). Best of three starts."""
    def sse(p):
        e, _ = _run(z, p, damped)
        return float(np.sum(e[PERIOD:] ** 2))
    best = None
    for x0 in STARTS[damped]:
        r = minimize(sse, np.array(x0, dtype=float), method="L-BFGS-B", bounds=BOUNDS[damped])
        if best is None or r.fun < best.fun - 1e-15:
            best = r
    return best.x, float(best.fun)


def aicc(z: np.ndarray, damped: bool) -> float:
    _, sse = fit(z, damped)
    n, k = len(z) - PERIOD, (4 if damped else 2)
    return n * math.log(sse / n) + 2 * k + 2 * k * (k + 1) / (n - k - 1)


def transform(key: str, y: np.ndarray) -> np.ndarray:
    return y.copy() if key in RAW_SCALE else np.log(y)


def untransform(key: str, z: np.ndarray) -> np.ndarray:
    return np.clip(z, 0.0, 1.0) if key in RAW_SCALE else np.exp(z)


def ets_forecast(key: str, y: np.ndarray, damped: bool, steps: int) -> np.ndarray:
    z = transform(key, y)
    p, _ = fit(z, damped)
    _, fc = _run(z, p, damped, steps)
    return untransform(key, fc)


def naive_growth(y: np.ndarray, steps: int) -> np.ndarray:
    """Last year's same month times the growth of the last three months over the same three months a year earlier."""
    n = len(y)
    g = y[n - 3:].sum() / y[n - 15:n - 12].sum()
    return np.array([y[n + h - 1 - PERIOD] * g for h in range(1, steps + 1)])


# ---------------------------------------------------------------- bridge

def bridge(actual: dict, plan: dict) -> dict:
    """Split actual minus plan revenue into volume, mix, trip length, rate per mile and charges per trip.

    The five pieces sum exactly to the miss: an identity (bookkeeping), not evidence."""
    def r_seg(d, s):
        return d[f"m_{s}"] * d[f"f_{s}"] + d[f"a_{s}"]

    # A segment with no actual trips has undefined actual ratios; it carries the plan's (its terms are zero anyway).
    a = dict(actual)
    for s in SEGMENTS:
        if a[f"w_{s}"] == 0:
            for k in ("m", "f", "a"):
                a[f"{k}_{s}"] = plan[f"{k}_{s}"]
    r_p = sum(plan[f"w_{s}"] * r_seg(plan, s) for s in SEGMENTS)
    Ta, Tp = a["T"], plan["T"]
    out = {
        "volume": (Ta - Tp) * r_p,
        "mix": Ta * sum((a[f"w_{s}"] - plan[f"w_{s}"]) * r_seg(plan, s) for s in SEGMENTS),
        "length": Ta * sum(a[f"w_{s}"] * (a[f"m_{s}"] - plan[f"m_{s}"]) * plan[f"f_{s}"] for s in SEGMENTS),
        "rate": Ta * sum(a[f"w_{s}"] * a[f"m_{s}"] * (a[f"f_{s}"] - plan[f"f_{s}"]) for s in SEGMENTS),
        "charges": Ta * sum(a[f"w_{s}"] * (a[f"a_{s}"] - plan[f"a_{s}"]) for s in SEGMENTS),
    }
    return out
