#!/usr/bin/env python3
"""Exact teaching counterexamples, not market data or a LOB-ID implementation.

Run with Python 3 and the standard library. Snapshots are independent static
probes: each sweep starts from an untouched book. No fills, fees, latency,
replenishment, queue positions or endogenous market impact are simulated.
"""

from collections import Counter
from fractions import Fraction
from math import isclose, sqrt
from statistics import mean, pvariance


def marginal_signature(rows):
    return tuple(Counter(column) for column in zip(*rows))


def sweep_cost_ticks(row, quantity=4):
    """Average price premium above the best ask, in ticks per unit."""
    remaining = quantity
    premium = 0
    for ticks_above_best, available in enumerate(row):
        filled = min(remaining, available)
        premium += ticks_above_best * filled
        remaining -= filled
        if remaining == 0:
            return Fraction(premium, quantity)
    raise ValueError("Insufficient displayed depth for the static probe")


def summarize(rows):
    costs = [sweep_cost_ticks(row) for row in rows]
    return {
        "mean_sweep_ticks": sum(costs, Fraction()) / len(rows),
        "reaches_level_3": Fraction(sum(a + b < 4 for a, b, _ in rows), len(rows)),
        "level_1_switch_rate": Fraction(
            sum(left[0] != right[0] for left, right in zip(rows, rows[1:])),
            len(rows) - 1,
        ),
    }


def main():
    # Fixed ask prices: 100.00, 100.01 and 100.02 USD; one tick = 0.01 USD.
    # The bid side can be held fixed and strictly below the best ask.
    reference = [(1, 1, 4)] * 4 + [(3, 3, 4)] * 4
    depth_permuted = [(1, 3, 4)] * 4 + [(3, 1, 4)] * 4
    time_permuted = [(1, 1, 4), (3, 3, 4)] * 4

    assert marginal_signature(reference) == marginal_signature(depth_permuted)
    assert marginal_signature(reference) == marginal_signature(time_permuted)
    assert [row[0] for row in reference] == [row[0] for row in depth_permuted]
    assert Counter(reference) == Counter(time_permuted)
    assert summarize(reference) == {
        "mean_sweep_ticks": Fraction(3, 4),
        "reaches_level_3": Fraction(1, 2),
        "level_1_switch_rate": Fraction(1, 7),
    }
    assert summarize(depth_permuted) == {
        "mean_sweep_ticks": Fraction(1, 2),
        "reaches_level_3": Fraction(0),
        "level_1_switch_rate": Fraction(1, 7),
    }
    assert summarize(time_permuted) == {
        "mean_sweep_ticks": Fraction(3, 4),
        "reaches_level_3": Fraction(1, 2),
        "level_1_switch_rate": Fraction(1),
    }

    print("Synthetic teaching example; not historical or live trading results.")
    print("All per-level marginal volume distributions match exactly.")
    for name, rows in (
        ("reference", reference),
        ("depth_permuted", depth_permuted),
        ("time_permuted", time_permuted),
    ):
        values = summarize(rows)
        print(name + ": " + ", ".join(f"{key}={value}" for key, value in values.items()))

    # Independent scalar-distribution example with equal population moments.
    first = [-1.0, -1.0, 1.0, 1.0]
    second = [-sqrt(2), 0.0, 0.0, sqrt(2)]
    assert isclose(mean(first), mean(second), abs_tol=1e-12)
    assert isclose(pvariance(first), pvariance(second), abs_tol=1e-12)
    gaussian_distance = (mean(first) - mean(second)) ** 2 + (
        sqrt(pvariance(first)) - sqrt(pvariance(second))
    ) ** 2
    wasserstein_squared = mean(
        (a - b) ** 2 for a, b in zip(sorted(first), sorted(second))
    )
    assert isclose(gaussian_distance, 0.0, abs_tol=1e-12)
    assert isclose(wasserstein_squared, 2 - sqrt(2), abs_tol=1e-12)
    print(f"Scalar Gaussian moment distance: {gaussian_distance:.6f}")
    print(f"Scalar squared Wasserstein-2: {wasserstein_squared:.6f}")
    print("PASS: exact snapshot invariants and scalar moment counterexample.")


if __name__ == "__main__":
    main()
