# /// script
# requires-python = ">=3.10"
# ///
# Copyright (c) 2026 Aayush Sharma · SPDX-License-Identifier: MIT
# https://thedataengineering.com/lab-code/LICENSE.txt
"""Retained window memory.

Tumbling windows of size W kept open until the watermark passes their end plus
an allowed lateness L. Counts the windows held at once for one key, as event
time advances minute by minute, against 1 + L/W.
"""
import argparse, json

p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
p.add_argument("--cases", default="1:10,1:20,60:10", help="W:L pairs in minutes.")
p.add_argument("--hours", type=int, default=24, help="Event time simulated (hours).")
p.add_argument("--json", help="Also write the results to this JSON file.")
args = p.parse_args()

rows = []
for case in args.cases.split(","):
    W, L = map(int, case.split(":")); held = []
    for t in range(args.hours * 60 * 60):                                # one tick per second of event time
        wm = t / 60                                                       # watermark, in minutes
        first_open = int(max(0, wm - L) // W)                             # windows whose end + L is still ahead of the watermark
        last = int(wm // W)
        held.append(last - first_open + 1)
    rows.append({"W_min": W, "L_min": L, "mean_held": sum(held) / len(held), "max_held": max(held), "formula": 1 + L / W})
for r in rows: print(f"W = {r['W_min']:>2} min, L = {r['L_min']:>2} min: windows held on average {r['mean_held']:6.2f}, at most {r['max_held']}   (1 + L/W = {r['formula']:.2f})")

if args.json:
    with open(args.json, "w") as f:
        json.dump({"tables": {"cases": rows}}, f)
