from __future__ import annotations

import argparse
import json
import sys
import urllib.error
import urllib.request


def main() -> int:
    parser = argparse.ArgumentParser(description="Generate a RecentlyOnScope digest via the State Hub API.")
    parser.add_argument("--domain", required=True, help="Domain slug, for example custodian")
    parser.add_argument("--range", default="1h", help="Time range such as 15m, 1h, 6h, or 1d")
    parser.add_argument("--since", help="Optional ISO timestamp for the start of the window")
    parser.add_argument("--until", help="Optional ISO timestamp for the end of the window")
    parser.add_argument("--api-base", default="http://127.0.0.1:8000", help="State Hub API base URL")
    parser.add_argument("--print-markdown", action="store_true", help="Print the generated Markdown instead of metadata")
    args = parser.parse_args()

    payload = {"range": args.range}
    if args.since:
        payload["since"] = args.since
    if args.until:
        payload["until"] = args.until

    url = f"{args.api_base.rstrip('/')}/domains/{args.domain}/recently-on-scope/"
    request = urllib.request.Request(
        url,
        data=json.dumps(payload).encode("utf-8"),
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(request, timeout=30) as response:
            body = json.loads(response.read().decode("utf-8"))
    except urllib.error.HTTPError as exc:
        detail = exc.read().decode("utf-8")
        print(f"State Hub returned {exc.code}: {detail}", file=sys.stderr)
        return 1
    except urllib.error.URLError as exc:
        print(f"Could not reach State Hub at {args.api_base}: {exc.reason}", file=sys.stderr)
        return 1

    if args.print_markdown:
        print(body["markdown"])
    else:
        print(json.dumps({key: value for key, value in body.items() if key != "markdown"}, indent=2))
    return 0


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