"""Month-ahead and week-ahead forecasts of orders, and the miss bridge. Standard library only, so it replays from the
stored daily table with no access to the export. Usage: python3 -I -B tools/forecast.py <results/daily_by_channel.csv>
"""
import csv
import json
import math
import sys

MONTH_ORIGINS = [28, 35, 42, 49, 56, 63]
NON_OVERLAP = [28, 56]
WEEK_ORIGINS = [28, 35, 42, 49, 56, 63, 70, 77, 84]


def read_daily(path, orders_col="orders"):
    rows = list(csv.DictReader(open(path, encoding="utf-8")))
    days = sorted({r["d"] for r in rows})
    chans = sorted({r["ch"] for r in rows})
    ix = {d: i for i, d in enumerate(days)}
    sess = {c: [0] * len(days) for c in chans}
    orders = {c: [0] * len(days) for c in chans}
    for r in rows:
        sess[r["ch"]][ix[r["d"]]] = int(r["sessions"])
        orders[r["ch"]][ix[r["d"]]] = int(r[orders_col])
    return days, chans, sess, orders


def window(series, a, b):
    return sum(series[a:b])


def rates(chans, sess, orders, t):
    out = {}
    for c in chans:
        s = window(sess[c], t - 28, t)
        out[c] = window(orders[c], t - 28, t) / s if s else 0.0
    return out


def miss_pct(forecast, actual):
    return 100.0 * (forecast - actual) / actual if actual else None


def month_ahead(days, chans, sess, orders):
    total = [sum(orders[c][i] for c in chans) for i in range(len(days))]
    rows = []
    for t in MONTH_ORIGINS:
        act = window(total, t, t + 28)
        cr = rates(chans, sess, orders, t)
        s_fc = {c: 4 * window(sess[c], t - 7, t) for c in chans}
        fc = {"N28": float(window(total, t - 28, t)), "N7": 4.0 * window(total, t - 7, t),
              "S": sum(s_fc[c] * cr[c] for c in chans)}
        bridge = {}
        for c in chans:
            s_act = window(sess[c], t, t + 28)
            o_act = window(orders[c], t, t + 28)
            r_act = o_act / s_act if s_act else cr[c]
            traffic = (s_act - s_fc[c]) * cr[c]
            conv = o_act - s_act * cr[c] if s_act else o_act
            bridge[c] = {"forecast_sessions": s_fc[c], "actual_sessions": s_act, "forecast_rate": cr[c], "actual_rate": r_act,
                         "traffic": traffic, "conversion": conv}
        closes = sum(b["traffic"] + b["conversion"] for b in bridge.values())
        assert abs(closes - (act - fc["S"])) < 1e-6, "bridge does not close"
        top = max(chans, key=lambda c: abs(bridge[c]["traffic"]) + abs(bridge[c]["conversion"]))
        top_part = max(((c, p) for c in chans for p in ("traffic", "conversion")), key=lambda x: abs(bridge[x[0]][x[1]]))
        rows.append({"origin_index": t, "origin_day": days[t], "horizon_end_day": days[t + 27], "actual": act, "forecast": fc,
                     "miss_pct": {m: miss_pct(v, act) for m, v in fc.items()}, "bridge": bridge,
                     "traffic_total": sum(b["traffic"] for b in bridge.values()),
                     "conversion_total": sum(b["conversion"] for b in bridge.values()),
                     "largest_channel": top, "largest_part": {"channel": top_part[0], "part": top_part[1],
                                                               "orders": bridge[top_part[0]][top_part[1]]}})
    return rows


def sign_test_two_sided(wins, n):
    k = max(wins, n - wins)
    return min(1.0, 2 * sum(math.comb(n, i) for i in range(k, n + 1)) / 2 ** n)


def week_ahead(days, chans, sess, orders):
    total = [sum(orders[c][i] for c in chans) for i in range(len(days))]
    rows = []
    for t in WEEK_ORIGINS:
        act = window(total, t, t + 7)
        cr = rates(chans, sess, orders, t)
        fc = {"N7w": float(window(total, t - 7, t)), "S7": sum(window(sess[c], t - 7, t) * cr[c] for c in chans)}
        rows.append({"origin_index": t, "origin_day": days[t], "actual": act, "forecast": fc,
                     "miss_pct": {m: miss_pct(v, act) for m, v in fc.items()}})
    usable = [r for r in rows if r["actual"]]
    wins = sum(abs(r["forecast"]["S7"] - r["actual"]) < abs(r["forecast"]["N7w"] - r["actual"]) for r in usable)
    ties = sum(abs(r["forecast"]["S7"] - r["actual"]) == abs(r["forecast"]["N7w"] - r["actual"]) for r in usable)
    n = len(usable) - ties
    return {"rows": rows, "S7_wins": wins, "ties": ties, "origins_compared": n, "p_two_sided": sign_test_two_sided(wins, n) if n else None}


def score_month(rows):
    out = {}
    for m in ("N28", "N7", "S"):
        ab = [abs(r["miss_pct"][m]) for r in rows]
        out[m] = {"mean_abs_miss_pct": sum(ab) / len(ab), "median_abs_miss_pct": sorted(ab)[len(ab) // 2 - 1] / 2 + sorted(ab)[len(ab) // 2] / 2,
                  "origins_missing_25_pct_or_more": sum(a >= 25 for a in ab),
                  "non_overlapping": {str(r["origin_index"]): r["miss_pct"][m] for r in rows if r["origin_index"] in NON_OVERLAP}}
    wins = {b: sum(abs(r["forecast"]["S"] - r["actual"]) < abs(r["forecast"][b] - r["actual"]) for r in rows) for b in ("N28", "N7")}
    return out, wins


def run(path, orders_col="orders"):
    days, chans, sess, orders = read_daily(path, orders_col)
    assert len(days) == 92, len(days)
    month = month_ahead(days, chans, sess, orders)
    scores, wins = score_month(month)
    return {"days": [days[0], days[-1]], "channels": chans, "month_ahead": month, "month_scores": scores, "S_wins_against": wins,
            "week_ahead": week_ahead(days, chans, sess, orders), "orders_per_day": [sum(orders[c][i] for c in chans) for i in range(len(days))]}


if __name__ == "__main__":
    print(json.dumps(run(sys.argv[1]), indent=1))
