#!/usr/bin/env python3
"""Pull peak usage from a sesinetd over the public API (cmd_get_peak_usage).

  ./peak_usage_pull.py
  ./peak_usage_pull.py --all
  ./peak_usage_pull.py --from "Wed, 12 Aug 2026 00:00:00 GMT"
  ./peak_usage_pull.py --raw
"""

import argparse
import json
import urllib.error
import urllib.parse
import urllib.request


def call(url, function, **kwargs):
    body = urllib.parse.urlencode(
        {"json": json.dumps([function, [], kwargs])}).encode()
    req = urllib.request.Request(
        url, data=body,
        headers={"Content-Type": "application/x-www-form-urlencoded"})
    with urllib.request.urlopen(req) as resp:
        return json.load(resp)


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--server", default="http://localhost:1715/api")
    p.add_argument("--all", action="store_true",
                   help="every interval, not just the most recent")
    p.add_argument("--from", dest="from_time", metavar="UTC",
                   help='e.g. "Wed, 12 Aug 2026 00:00:00 GMT"')
    p.add_argument("--to", dest="to_time", metavar="UTC")
    p.add_argument("--raw", action="store_true", help="print the JSON reply")
    args = p.parse_args()

    kwargs = {}
    if args.all:
        kwargs["all"] = True
    if args.from_time:
        kwargs["from"] = args.from_time
    if args.to_time:
        kwargs["to"] = args.to_time

    try:
        reply = call(args.server, "cmd_get_peak_usage", **kwargs)
    except urllib.error.HTTPError as err:
        # The server explains a refused request in the body, so print it.
        print("%s %s: %s" % (err.code, err.reason, err.read().decode().strip()))
        return 1

    if args.raw:
        print(json.dumps(reply, indent=4))
        return 0

    names = {lic["id"]: lic["prod_name"] for lic in reply["licenses"]}

    print("server %s" % reply["version"])
    for interval in reply["usage"]:
        print("\n%s" % interval["timestamp"])
        for value in interval["values"]:
            print("    %4d  %s (%s)" % (
                value["peak"], names.get(value["id"], "?"), value["id"]))
    if not reply["usage"]:
        # Only closed intervals are reported, so a fresh checkout shows nothing
        # until the interval ends.
        print("\nno closed interval with usage in it yet")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
