"""Proof of Foresight, protocol 1.0: baselines B0 and B1, model M1, pseudo-out-of-sample errors and intervals.
Pure Python (no numpy) so that anyone can rerun it. Everything is deterministic: same input file -> same output bytes.
Values are Rosstat monthly average consumer prices (roubles), units are federal subjects, periods 'YYYY-MM'."""
import math, statistics as st

MODEL_VERSION = 'm1-2026.11.1'
QUANTILES = [0.05, 0.25, 0.5, 0.75, 0.95]
STICKY_SHARE = 0.6        # a series is "administered" if >= 60% of region-months show no change
CONTINUOUS_SHARE = 0.2   # below 20% unchanged region-months a series is "continuous" (rents)
STEP_SHARE = 0.5          # a month is a "step month" of a series if > 50% of regions changed the price that month
DRIFT_WINDOW = 6          # months of history for B1
MIN_ERRORS = 30           # below this many backtest errors a series borrows its class's pooled errors

def add(p, k):
    y, m = map(int, p.split('-')); m += k; y += (m - 1) // 12; m = (m - 1) % 12 + 1
    return f'{y:04d}-{m:02d}'

def changes(H, s, upto):
    """monthly log changes {(region, period): dlog} for series s up to and including period upto"""
    out = {}
    for (p, r, ss), v in H.items():
        if ss != s or p > upto: continue
        q = add(p, -1)
        if (q, r, s) in H and H[(q, r, s)] > 0 and v > 0: out[(r, p)] = math.log(v / H[(q, r, s)])
    return out

def profile(H, s, upto):
    ch = changes(H, s, upto)
    zero = sum(1 for x in ch.values() if abs(x) < 1e-9) / max(1, len(ch))
    per = {}
    for (r, p), x in ch.items(): per.setdefault(p, []).append(abs(x) > 1e-9)
    steps = sorted(p for p, xs in per.items() if sum(xs) / len(xs) > STEP_SHARE)
    cls = 'administered' if zero >= STICKY_SHARE else 'continuous' if zero < CONTINUOUS_SHARE else 'lumpy'
    regs = sorted({r for (r, p) in ch})
    drifts = [drift_region(ch, r, upto, DRIFT_WINDOW) for r in regs]
    common = st.median([m for m, n, xs in drifts if n]) if drifts else 0.0
    return {'class': cls, 'sticky': cls == 'administered', 'zero_share': round(zero, 3), 'step_months': steps, 'common_drift': common, 'changes': ch}

def drift_region(ch, r, upto, window):
    xs = [x for (rr, p), x in ch.items() if rr == r and add(upto, -window) < p <= upto]
    return (sum(xs) / len(xs), len(xs), xs) if xs else (0.0, 0, [])

def points(H, s, r, last, h, prof):
    """point forecasts for target add(last, h) from information up to period last"""
    y = H.get((last, r, s))
    if not y: return None
    ch = prof['changes']
    d6, _, _ = drift_region(ch, r, last, DRIFT_WINDOW)
    b0 = y; b1 = y * math.exp(h * d6)
    if prof['class'] == 'continuous':
        # prices that move almost every month (rents): the last value carried forward with the common monthly change,
        # i.e. the cross-region median of each region's mean change over the last DRIFT_WINDOW months
        m1 = y * math.exp(h * prof['common_drift'])
    else:
        # administered (tariffs, fees) and lumpy (clinic price lists) series change in steps;
        # between steps the last value is the forecast, and the uncertainty about a step lives in the interval
        m1 = y
    return {'b0': b0, 'b1': b1, 'm1': m1}

def backtest(H, series, last, horizons=(1, 2), first_origin=None):
    """pseudo-out-of-sample log errors of M1 (actual - forecast) for every origin o with o+h <= last,
    using only information up to o. Returns {s: {h: [(origin, target, region, err, target_is_step)]}}"""
    periods = sorted({p for (p, r, s) in H})
    first_origin = first_origin or periods[2]
    out = {}
    for s in series:
        out[s] = {h: [] for h in horizons}
        steps_all = set(profile(H, s, last)['step_months'])
        for o in [p for p in periods if first_origin <= p <= last]:
            prof = profile(H, s, o)
            for h in horizons:
                t = add(o, h)
                if t > last: continue
                for r in sorted({rr for (p, rr, ss) in H if ss == s and p == o}):
                    f = points(H, s, r, o, h, prof); a = H.get((t, r, s))
                    if f and a: out[s][h].append((o, t, r, math.log(a / f['m1']), t in steps_all or any(add(o, k) in steps_all for k in range(1, h + 1))))
    return out

def quantile(xs, q):
    xs = sorted(xs); i = q * (len(xs) - 1); lo = math.floor(i); hi = math.ceil(i)
    return xs[lo] + (xs[hi] - xs[lo]) * (i - lo)

def error_quantiles(bt, s, h, sticky, target_is_step, pooled):
    """empirical quantiles of log errors. For administered series and a target window without a known step month,
    only errors from windows without a step are used (the step calendar is learned from the data, not assumed)."""
    errs = [e for (o, t, r, e, stp) in bt[s][h] if not sticky or stp == target_is_step]
    src = 'series'
    if len(errs) < MIN_ERRORS:
        errs = pooled; src = 'class'
    qs = [quantile(errs, q) for q in QUANTILES]
    qs[2] = 0.0 if sticky and not target_is_step else qs[2]
    return qs, len(errs), src
