"""Inspect a bounded lock wait using CPython 3.10+ on Linux."""
import argparse
import faulthandler
import os
import signal
import threading
from pathlib import Path


def worker(lock):
    with lock:
        print("WORKER: acquired lock", flush=True)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--log", type=Path, default=Path("stacks.log"))
    parser.add_argument("--seconds", type=int, default=8)
    parser.add_argument("--interval", type=int, default=2)
    args = parser.parse_args()
    if not (1 <= args.seconds <= 3600 and 1 <= args.interval <= 3600):
        parser.error("seconds and interval must be between 1 and 3600")

    lock = threading.Lock()
    # Exclusive creation preserves stack logs from previous runs.
    with args.log.open("x", encoding="utf-8") as stack_log:
        faulthandler.register(signal.SIGUSR1, file=stack_log, all_threads=True)
        try:
            faulthandler.dump_traceback_later(
                args.interval, repeat=True, file=stack_log, exit=False
            )
            with lock:
                thread = threading.Thread(target=worker, args=(lock,))
                thread.start()
                # Registration is complete before these readiness messages.
                print(f"READY pid={os.getpid()}", flush=True)
                print(f"SNAPSHOT: kill -USR1 {os.getpid()}", flush=True)
                thread.join(timeout=args.seconds)
            # Releasing the lock lets the waiting worker finish.
            thread.join()
        finally:
            faulthandler.cancel_dump_traceback_later()
            faulthandler.unregister(signal.SIGUSR1)
    print(f"DONE: {args.log}", flush=True)


if __name__ == "__main__":
    main()
