#!/usr/bin/env python3
"""Exact periodic-timetable teaching model; no real transit data or random sampling.

Default: standard-library JSON report to stdout.
Optional --plot FILE.svg: also write the original illustration (needs Matplotlib).
"""
import argparse
from bisect import bisect_left
from collections import Counter
from fractions import Fraction
import json
from pathlib import Path
import platform


def validate(headways):
    if not headways or any(type(h) is not int or h < 0 for h in headways):
        raise ValueError('Use a nonempty sequence of nonnegative integer-minute gaps')
    if sum(headways) == 0:
        raise ValueError('A cycle must have positive duration')
    return list(headways)


def departures(headways):
    times = [0]
    for h in headways:
        times.append(times[-1] + h)
    return times


def wait_at(arrival, headways):
    headways = validate(headways)
    times = departures(headways)
    phase = Fraction(arrival) % times[-1]
    # Arrival exactly at a departure boards immediately in this teaching model.
    return Fraction(times[bisect_left(times, phase)]) - phase


def survival(threshold, headways):
    threshold = Fraction(threshold)
    if threshold < 0:
        return Fraction(1)
    return Fraction(sum(max(Fraction(h) - threshold, 0) for h in headways), sum(headways))


def quantile(probability, headways):
    probability = Fraction(probability)
    assert 0 <= probability <= 1
    if probability == 0:
        return Fraction(0)
    target_area = probability * sum(headways)
    accumulated = Fraction(0)
    left = 0
    for right in sorted(set(headways) - {0}):
        active = sum(h > left for h in headways)
        area = active * (right - left)
        if target_area <= accumulated + area:
            return Fraction(left) + (target_area - accumulated) / active
        accumulated += area
        left = right
    raise AssertionError('Quantile interval not found')


def number(value):
    value = Fraction(value)
    return {'fraction': str(value), 'decimal': float(value)}


def analyze(name, headways):
    headways = validate(headways)
    total = sum(headways)
    n = len(headways)
    mean = Fraction(total, n)
    variance = sum((Fraction(h) - mean)**2 for h in headways) / n
    expected_wait = Fraction(sum(h*h for h in headways), 2*total)
    assert expected_wait == mean/2 + variance/(2*mean)
    thresholds = [0, 5, 10, 15, 20, 30]
    # Independent lookup over every one-second cell's midpoint in the cycle.
    # All departure/threshold boundaries here lie on cell edges, so midpoint
    # integration of the linear wait is exact, not a Monte Carlo estimate.
    points = total * 60
    waits = []
    seen = Counter()
    ends = departures(headways)[1:]
    for tick in range(points):
        phase = Fraction(2*tick+1, 120)
        waits.append(wait_at(phase, headways))
        seen[bisect_left(ends, phase)] += 1
    grid_mean = sum(waits) / points
    assert grid_mean == expected_wait
    tails = []
    for threshold in thresholds:
        analytic = survival(threshold, headways)
        enumerated = Fraction(sum(w > threshold for w in waits), points)
        assert analytic == enumerated
        tails.append({'waitGreaterThanMinutes': threshold, 'probability': number(analytic)})
    time_weights = [Fraction(h, total) for h in headways]
    assert [Fraction(seen[i], points) for i in range(n)] == time_weights
    q90 = quantile(Fraction(9, 10), headways)
    assert 1-survival(q90, headways) == Fraction(9, 10)
    return {
        'name': name, 'headwaysMinutes': headways, 'departuresInCycle': departures(headways),
        'cycleMinutes': total, 'headwayCount': n,
        'meanHeadwayMinutes': number(mean),
        'populationVarianceMinutesSquared': number(variance),
        'meanWaitUniformTimeMinutes': number(expected_wait),
        'meanWaitEqualIntervalThenUniformWithinMinutes': number(mean/2),
        'timeEncounterProbabilities': [number(p) for p in time_weights],
        'meanEncounteredIntervalMinutes': number(Fraction(sum(h*h for h in headways), total)),
        'wait90thPercentileMinutes': number(q90),
        'survival': tails,
        'midpointCheck': {'points': points, 'cellSeconds': 1,
                          'meanWaitMinutes': number(grid_mean), 'allTailChecksMatched': True},
    }


def draw_plot(path):
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt
    matplotlib.rcParams.update({'font.family': 'DejaVu Sans', 'svg.fonttype': 'none',
                                'svg.hashsalt': 'gumi-headway-20261102', 'font.size': 11})
    fig, axes = plt.subplots(2, 1, figsize=(10, 6.6), sharex=True, sharey=True)
    colors = ['#2563eb', '#c2410c']
    for axis, gaps, title in zip(axes, ([10, 10], [1, 19]),
                                ('Regular: 10 + 10 minutes', 'Uneven: 1 + 19 minutes')):
        start = 0
        for i, h in enumerate(gaps):
            end = start+h
            axis.fill_between([start, end], [h, 0], color=colors[i], alpha=0.18)
            axis.plot([start, end], [h, 0], color=colors[i], linewidth=2.1)
            axis.scatter([start], [h], facecolors='white', edgecolors=colors[i], zorder=4, s=32)
            axis.text((start+end)/2, -2.0, f'{h} min gap', ha='center', fontsize=10)
            start = end
        times = departures(gaps)
        axis.scatter(times, [0]*len(times), color='#0f172a', marker='o', zorder=5, s=28)
        mean_wait = sum(h*h for h in gaps)/(2*sum(gaps))
        axis.axhline(mean_wait, color='#334155', linestyle='--', linewidth=1.1)
        axis.text(20.3, mean_wait, f'mean {mean_wait:g}', va='center', fontsize=10,
                  bbox={'facecolor': 'white', 'edgecolor': 'none', 'pad': 2})
        axis.set_title(title, loc='left', fontweight='bold', pad=9)
        axis.set_ylabel('Wait to next bus (min)')
        axis.set_xlim(-0.2, 23.3)
        axis.set_ylim(-3.1, 20.5)
        axis.set_yticks([0, 5, 10, 15, 20])
        axis.grid(axis='y', color='#cbd5e1', alpha=0.6, linewidth=0.7)
        axis.spines[['top', 'right']].set_visible(False)
    axes[1].set_xticks([0, 1, 5, 10, 15, 20])
    axes[1].set_xlabel('Arrival phase in a repeating 20-minute cycle')
    fig.subplots_adjust(left=0.10, right=0.95, top=0.93, bottom=0.15, hspace=0.38)
    fig.text(0.10, 0.035, 'Synthetic timetable; uniform arrival time; next bus always boardable.\n'
             'Slopes show interval interiors. Dots at departures mean immediate boarding (zero wait).',
             fontsize=9, color='#334155')
    fig.savefig(path, format='svg', metadata={'Date': None, 'Creator': 'Gumi / Matplotlib'})
    fig.savefig(path.with_suffix('.png'), dpi=160)
    plt.close(fig)
    # Make version-control whitespace stable without changing SVG content.
    path.write_text('\n'.join(line.rstrip() for line in path.read_text().splitlines())+'\n')


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--plot', type=Path, help='Also write SVG and preview PNG; requires Matplotlib')
    args = parser.parse_args()
    schedules = [
        ('regular', [10, 10]), ('moderate', [5, 15]), ('bunched', [1, 19]),
        ('long-gap', [1, 1, 28]), ('simultaneous', [0, 20]),
        ('single-gap', [10]), ('reversed', [19, 1]),
    ]
    cases = [analyze(name, gaps) for name, gaps in schedules]
    assert cases[0]['meanWaitUniformTimeMinutes']['fraction'] == '5'
    assert cases[1]['meanWaitUniformTimeMinutes']['fraction'] == '25/4'
    assert cases[2]['meanWaitUniformTimeMinutes']['fraction'] == '181/20'
    assert cases[3]['meanWaitUniformTimeMinutes']['fraction'] == '131/10'
    assert cases[4]['meanWaitUniformTimeMinutes']['fraction'] == '10'
    assert cases[2]['meanWaitUniformTimeMinutes'] == cases[6]['meanWaitUniformTimeMinutes']
    assert analyze('scaled', [2, 38])['meanWaitUniformTimeMinutes']['fraction'] == '181/10'
    assert cases[2]['survival'][1]['probability']['fraction'] == '7/10'
    assert cases[2]['wait90thPercentileMinutes']['fraction'] == '17'
    invalid = [[], [0, 0], [-1, 21], [True, 19], [1.0, 19], ['1', 19], [None, 19]]
    for gaps in invalid:
        try:
            validate(gaps)
        except ValueError:
            pass
        else:
            raise AssertionError('Invalid input accepted')
    boundary_queries = [(0, 0), (1, 0), (20, 0), (21, 0), (19, 1),
                        (Fraction(1, 2), Fraction(1, 2)),
                        (Fraction(3, 2), Fraction(37, 2)), (-1, 1)]
    for arrival, expected in boundary_queries:
        assert wait_at(arrival, [1, 19]) == expected
    planned_arrivals = [9, 19]
    planned_wait = sum(wait_at(t, [10, 10]) for t in planned_arrivals)/len(planned_arrivals)
    assert planned_wait == 1
    report = {
        'experiment': 'Exact synthetic periodic timetables; independent uniform arrival phase',
        'runDate': '2026-11-02',
        'environment': {'python': platform.python_version(), 'system': platform.system(),
                        'macOS': platform.mac_ver()[0], 'machine': platform.machine()},
        'cases': cases,
        'plannedArrivalCounterexample': {'headwaysMinutes': [10, 10],
            'arrivalPhasesMinutes': planned_arrivals, 'meanWaitMinutes': number(planned_wait)},
        'boundaryQueries': [{'arrivalMinutes': str(a), 'waitMinutes': str(w)} for a, w in boundary_queries],
        'checks': {'reportedSchedules': len(cases), 'invalidInputsRejected': len(invalid),
                   'boundaryQueries': len(boundary_queries),
                   'exactVarianceIdentityAndMidpointChecksPassed': True,
                   'orderAndScaleChecksPassed': True, 'allAssertionsPassed': True},
        'limits': [
            'Synthetic repeating timetable, not observations or predictions for an actual transit route.',
            'Arrival phase is continuous uniform and independent of departures; every next bus is boardable.',
            'There is no last-bus cutoff, finite capacity, transfer, walking time or changing demand.',
            'Integer-minute gaps permit exact one-second midpoint integration; no random draws were used.',
            'Variance uses the finite cycle population divisor n, not the sample estimator divisor n-1.',
        ],
    }
    if args.plot:
        if args.plot.suffix != '.svg':
            parser.error('--plot path must end in .svg')
        draw_plot(args.plot)
    print(json.dumps(report, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    main()
