"""BETro's on-time index and settlement, as the methodology page gives them.

https://betro.live/methodology. Python 3.10 or later, standard library only.
The scoring walk gives the same results as the index engines (DC's
whatsthewmata index_engine/score.py, method version 4, and New York's copy
in betro-nyc); merge() is DC's and observe() New York's. result() and
seed() follow trainwatch's pool.py, and trainwatch's tests check them
against it (tests/test_methodology_code.py).
"""
from collections import defaultdict
from dataclasses import dataclass
from datetime import timedelta
from fractions import Fraction
from math import floor

SLACK = 180              # seconds a gap may run over and still be on time


@dataclass(frozen=True)
class Slot:
    at: int              # scheduled time, seconds
    g_in: int | None     # scheduled gap from the slot before (None for the first)
    g_out: int | None    # scheduled gap to the slot after (None for the last)


@dataclass(frozen=True)
class Train:
    at: float            # the time scored
    source: str          # "rt" (feed), "board" or "both"
    trip_time: int | None = None   # its trip's scheduled time here, if known


def slots(trips):
    """One day's slots, by platform: (line, direction, station).

    trips: the day's trips from the timetable above, each with .line,
    .direction and .stops (station, arrival, departure) in order.
    """
    times = defaultdict(list)
    for trip in trips:
        for k, stop in enumerate(trip.stops[:-1]):      # no slot at the last stop
            t = stop.departure if k == 0 else stop.arrival
            times[(trip.line, trip.direction, stop.station)].append(t)
    out = {}
    for platform, ts in times.items():
        ts.sort()
        out[platform] = [Slot(t,
                              g_in=t - ts[i - 1] if i > 0 else None,
                              g_out=ts[i + 1] - t if i + 1 < len(ts) else None)
                         for i, t in enumerate(ts)]
    return out


BOARD_LAG = 14           # median seconds from arrival to the board showing BRD
PAIR_WINDOW = 120        # feed and board arrivals further apart are different trains
UNSEEN_PASS = (-300, 30) # a board train this near a passed_unobserved visit is that train


def merge(visits, board_times):
    """One platform's trains for one day, and the times of passes nobody saw.

    visits: feed visits, already without each trip's last stop or a vehicle
    repeated under another trip, with .at, .outcome and .trip_time.
    board_times: when the boards first showed each train boarding here.
    """
    seen = [v for v in visits if v.outcome != "passed_unobserved"]
    passes = [v for v in visits if v.outcome == "passed_unobserved"]

    # Pair feed and board arrivals one to one, nearest first.
    pairs = sorted((abs(b - v.at), i, j) for i, v in enumerate(seen)
                   for j, b in enumerate(board_times) if abs(b - v.at) <= PAIR_WINDOW)
    used_v, used_b, trains = set(), set(), []
    for _, i, j in pairs:
        if i not in used_v and j not in used_b:
            used_v.add(i)
            used_b.add(j)
            trains.append(Train(seen[i].at, "both", seen[i].trip_time))
    trains += [Train(v.at, "rt", v.trip_time)
               for i, v in enumerate(seen) if i not in used_v]
    board_only = [Train(b - BOARD_LAG, "board")
                  for j, b in enumerate(board_times) if j not in used_b]

    # A passed_unobserved visit is a train if the boards saw it, else a hole.
    unseen = []
    for p in passes:
        near = [b for b in board_only if UNSEEN_PASS[0] <= b.at - p.at <= UNSEEN_PASS[1]]
        if near:
            b = min(near, key=lambda b: abs(b.at - p.at))
            board_only.remove(b)
            trains.append(Train(b.at, "board", p.trip_time))
        else:
            unseen.append(p.at)
    trains += board_only
    return sorted(trains, key=lambda t: t.at), sorted(unseen)


def observe(visits):
    """One platform's trains for one day, and the times of passes nobody
    saw (New York).

    visits: feed visits, already without each trip's last stop or a train
    repeated under another trip id, with .at, .outcome and .trip_time.
    """
    trains = [Train(v.at, "rt", v.trip_time) for v in visits if v.outcome == "arrived"]
    unseen = [v.at for v in visits if v.outcome in ("passed_unobserved", "trip_vanished")]
    return sorted(trains, key=lambda t: t.at), sorted(unseen)


def score_platform(slots, trains, holes=(), unseen=(), slack=SLACK):
    """One (status, extra wait in seconds) per slot at one platform.

    slots and trains in time order; holes: (start, end) stretches no source
    could see; unseen: times of passes nobody saw.
    """
    t = [s.at for s in slots]
    own = {s.at: i for i, s in enumerate(slots)}   # each slot's index by its time
    results = []
    base = None                      # when the last serving train came
    prev = t[0] - 1800 if t else 0   # end of the last slot's window
    k = 0                            # the next unused train
    drift = 0                        # missed slots not yet caught up
    for i, slot in enumerate(slots):
        g_in = slot.g_in or 0
        g_out = slot.g_out if slot.g_out is not None else g_in

        def due():
            return t[i] + slack if base is None else base + g_in + slack

        deadline = due()
        # After a missed slot, a bunched train moves the base but serves no slot.
        while drift and k < len(trains) and bunched_extra(trains[k], i, t, own):
            base = trains[k].at
            k += 1
            drift -= 1
            deadline = due()
        end = deadline + g_out
        c = trains[k] if k < len(trains) and trains[k].at <= end else None
        if c and i + 1 < len(t) and c.at > t[i + 1] + slack:
            c, end = None, max(deadline, t[i + 1] + slack)   # it belongs to a later slot
        d = c.at if c else end
        if overlaps(holes, prev, d) or any(prev < u <= d for u in unseen):
            results.append(("unobserved", None))
            base, drift = (c.at if c else None), 0
        elif c and c.at <= deadline:
            results.append(("on_time", 0))
            base = c.at
        elif c:
            results.append(("late", round(c.at - deadline)))
            base = c.at
        else:
            results.append(("missed", g_out))
            base = t[i] if base is None else base + g_in
            drift += 1
        # A train due at the next slot may serve that one too, so it isn't used up.
        if c and own.get(c.trip_time) != i + 1:
            k += 1
        prev = d
    return results


def bunched_extra(train, i, t, own):
    """Whether a train is the extra a missed slot left behind."""
    if train.at >= t[i]:
        return False                 # not early for this slot: let it serve
    if own.get(train.trip_time) is not None:
        return own[train.trip_time] < i
    return i > 0 and train.at < t[i - 1]   # no trip identity: early for the slot before


def overlaps(holes, a, b):
    return any(h0 < b and h1 > a for h0, h1 in holes)


@dataclass
class Tally:
    slots: int = 0
    observed: int = 0
    on_time: int = 0
    extra_wait: int = 0              # seconds

    @property
    def share(self):                 # the on-time share
        return Fraction(self.on_time, self.observed)

    @property
    def coverage(self):
        return Fraction(self.observed, self.slots)


def roll_up(results):
    """{(line, direction, station): [(status, extra)]} -> {scope: Tally}, where a
    scope is "system", ("line", line) or ("station", station)."""
    out = defaultdict(Tally)
    for (line, _, station), rs in results.items():
        for status, extra in rs:
            for scope in ("system", ("line", line), ("station", station)):
                x = out[scope]
                x.slots += 1
                if status != "unobserved":
                    x.observed += 1
                    x.on_time += status == "on_time"
                    x.extra_wait += extra
    return out


MIN_COVERAGE = Fraction(9, 10)


def covered(tally):
    return tally is not None and tally.slots > 0 and tally.coverage >= MIN_COVERAGE


def result(market, scores):
    """(winners, void outcomes), or None if the market is called off.

    market.kind is "line", "station" or "range"; market.pick "best" or
    "worst"; a range outcome has .low and .high (None for open ends).
    """
    if not covered(scores["system"]):
        return None
    if market.kind == "range":
        p = 100 * scores["system"].share
        return [o for o in market.outcomes
                if (o.low is None or p >= o.low) and (o.high is None or p < o.high)], set()
    live = {o: scores[(market.kind, o)] for o in market.outcomes
            if covered(scores.get((market.kind, o)))}
    sign = 1 if market.pick == "best" else -1
    # Highest share wins a best market; ties go to the least extra wait (most, for worst).
    rank = {o: (sign * x.share, -sign * x.extra_wait) for o, x in live.items()}
    top = max(rank.values(), default=None)
    return [o for o in live if rank[o] == top], set(market.outcomes) - set(live)


def payouts(stakes, outcome):
    """Points back to each player, from [(player, outcome, points)] stakes
    with the house seed among them. Rounding leaves the rest to the house."""
    back = defaultdict(int)
    if outcome is None:                              # called off: every stake back
        for player, _, points in stakes:
            back[player] += points
        return back
    winners, void = outcome
    live = []
    for player, o, points in stakes:
        if o in void:
            back[player] += points                   # under 90% coverage: refunded
        else:
            live.append((player, o, points))
    backed = {o for _, o, _ in live if o in winners}
    if not backed:                                   # nobody backed a winner
        for player, _, points in live:
            back[player] += points
        return back
    pool = sum(points for _, _, points in live)
    on = {w: sum(p for _, o, p in live if o == w) for w in backed}
    owed = defaultdict(Fraction)
    for player, o, points in live:
        if o in backed:                  # each backed winner: an equal part of the pool
            owed[player] += Fraction(pool * points, len(backed) * on[o])
    for player, x in owed.items():
        back[player] += floor(x)
    return back


def forecast(market, day, as_of, scored, group_of,
             window=30, weights=(Fraction(1, 2), Fraction(1, 2))):
    """The house's chance for each outcome of market on day, from the days
    scored in the window before as_of (when the market opens).

    scored: {date: scores}; group_of(date): "weekday", "weekend" or "holiday".
    """
    won = {}
    for n in range(window, 0, -1):
        past = as_of - timedelta(days=n)
        if past not in scored:
            continue
        r = result(market, scored[past])
        if r and r[0]:                               # a day some outcome won
            won[past] = {o: Fraction(o in r[0], len(r[0])) for o in market.outcomes}
    group = [d for d in won if group_of(d) == group_of(day)]
    weekday = [d for d in group if d.weekday() == day.weekday()]
    halves = [(w, ds) for w, ds in zip(weights, (group, weekday)) if w and ds]
    if not halves:
        if not won:
            return {o: Fraction(1, len(market.outcomes)) for o in market.outcomes}
        halves = [(1, list(won))]
    total = sum(w for w, _ in halves)
    return {o: sum(w / total * Fraction(sum(won[d][o] for d in ds), len(ds))
                   for w, ds in halves)
            for o in market.outcomes}


def seed(chances, total=1000):
    """Whole points per outcome by chance: largest remainder, ties to the earlier."""
    exact = [c * total for c in chances]
    points = [floor(x) for x in exact]
    order = sorted(range(len(exact)), key=lambda i: (points[i] - exact[i], i))
    for i in order[:total - sum(points)]:
        points[i] += 1
    return points
