"""wake_times.py - how long from giving the cashier a task to the task being done?

    python wake_times.py

Twenty orders, one after another, each timed from the request that creates the
task to the first moment the task reads "done".
"""
import statistics
import time

import scratch

ORDERS = 20


def main():
    made, boss = scratch.company("Check wake times")
    cashier = scratch.cashier(made, boss)
    seconds = []
    for number in range(ORDERS):
        began = time.time()
        task = scratch.send("POST", "/companies/" + made["id"] + "/issues",
                            {"title": f"Bill {number}", "description": "2 khao soi, 1 water",
                             "status": "todo", "assigneeAgentId": cashier["id"]})
        while task["status"] != "done":
            if time.time() - began > 60:
                raise SystemExit(f"order {number} was not done in 60 seconds")
            time.sleep(0.05)
            task = scratch.send("GET", "/issues/" + task["id"])
        seconds.append(time.time() - began)
    runs = scratch.send("GET", "/companies/" + made["id"] + "/heartbeat-runs")
    sources = sorted({run["invocationSource"] for run in runs})
    print(f"{ORDERS} orders, each given to the cashier and waited for.")
    print(f"Fastest: {min(seconds):.2f} seconds")
    print(f"Median: {statistics.median(seconds):.2f} seconds")
    print(f"Slowest: {max(seconds):.2f} seconds")
    print(f"Paperclip started the cashier {len(runs)} times. Started by: {', '.join(sources)}")
    scratch.remove(made)


if __name__ == "__main__":
    main()
