#!/usr/bin/env python3
"""Original synthetic FIFO and inventory accounting exercise for QuantSteps.

Run with Python 3: python hft-queue-example.py
Standard library only. No market data, API, broker access or trading signals.
Orders are already accepted; cancellations identify quantity ahead precisely.
No hidden liquidity, priority changes, impact or competing new orders in baseline.
Fees are fictional per-share assumptions; decimal arithmetic preserves cents.
The two exit scenarios are alternatives, never added together.
"""

from decimal import Decimal
import json


def fifo_replay(ahead, own_size, events):
    remaining = own_size
    filled = 0
    rows = []
    for kind, quantity in events:
        if kind == "cancel_ahead":
            if not 0 <= quantity <= ahead:
                raise ValueError("Cancellation exceeds identified quantity ahead")
            ahead -= quantity
        elif kind == "sell_trade":
            consumed_ahead = min(ahead, quantity)
            ahead -= consumed_ahead
            own_fill = min(remaining, quantity - consumed_ahead)
            remaining -= own_fill
            filled += own_fill
        elif kind == "cancel_own":
            if not 0 <= quantity <= remaining:
                raise ValueError("Own cancellation exceeds remaining order")
            remaining -= quantity
        else:
            raise ValueError("Unknown event")
        rows.append({"event": kind, "quantity": quantity, "ahead": ahead,
                     "filled": filled, "remaining": remaining})
    return {"filled": filled, "remaining": remaining, "ahead": ahead, "rows": rows}


def main():
    events = [("cancel_ahead", 100), ("sell_trade", 150), ("sell_trade", 90)]
    baseline = fifo_replay(300, 100, events)
    delayed = fifo_replay(500, 100, events)
    baseline_cancelled = fifo_replay(300, 100, events + [("cancel_own", 60)])
    assert baseline["filled"] == 40 and baseline["remaining"] == 60
    assert delayed["filled"] == 0 and delayed["remaining"] == 100
    assert baseline_cancelled["filled"] == 40 and baseline_cancelled["remaining"] == 0

    d = Decimal
    size = d(baseline["filled"])
    entry = d("99.99")
    maker_fee = d("0.001")
    taker_fee = d("0.003")
    passive_exit = size * (d("100.01") - entry) - size * 2 * maker_fee
    marked_pnl = size * (d("99.98") - entry) - size * maker_fee
    aggressive_exit = size * (d("99.97") - entry) - size * (maker_fee + taker_fee)
    assert passive_exit == d("0.720")
    assert marked_pnl == d("-0.440")
    assert aggressive_exit == d("-0.960")

    output = {
        "synthetic": True,
        "baseline_queue": baseline,
        "baseline_after_accepted_cancellation": baseline_cancelled,
        "extra_200_shares_ahead": delayed,
        "passive_exit_net_usd": str(passive_exit),
        "adverse_midpoint_mark_after_entry_fee_usd": str(marked_pnl),
        "aggressive_exit_net_usd": str(aggressive_exit),
        "exit_scenarios_are_alternatives": True,
    }
    print(json.dumps(output, indent=2))


if __name__ == "__main__":
    main()
