"""Read lottery JSON using a server-side LOTTO_API_KEY environment variable.""" import argparse import json import os import sys import requests BASE = "https://api.supapongai.com/api/v1" ROUTES = {"all": "/lotto/huay", "government": "/lotto", "hanoi": "/lotto/huay", "laos": "/lotto/huay", "yeekee": "/lotto/yeekee", "stock": "/lotto/stock", "thaiyen": "/lotto/thaiyen"} def main(): parser = argparse.ArgumentParser(description="Fetch lottery results as JSON") parser.add_argument("--category", choices=ROUTES, default="all") parser.add_argument("--limit", type=int) parser.add_argument("--date") args = parser.parse_args() if (args.limit is not None or args.date) and args.category != "thaiyen": parser.error("--limit and --date are documented only for thaiyen") if args.limit is not None and not 1 <= args.limit <= 500: parser.error("--limit must be between 1 and 500") key = os.environ.get("LOTTO_API_KEY") if not key: parser.error("Set LOTTO_API_KEY to your lotto-category API key") params = {} if args.category in ("hanoi", "laos"): params["type"] = args.category if args.limit is not None: params["limit"] = args.limit if args.date: params["date"] = args.date try: response = requests.get(BASE + ROUTES[args.category], headers={"X-API-KEY": key}, params=params, timeout=30) response.raise_for_status() payload = response.json() if isinstance(payload, dict) and payload.get("success") is False: print("API returned success=false; inspect your portal documentation.", file=sys.stderr) return 1 print(json.dumps(payload, ensure_ascii=False, indent=2)) return 0 except requests.exceptions.RequestException as error: status = getattr(getattr(error, "response", None), "status_code", None) print(f"Request failed ({'HTTP ' + str(status) if status else type(error).__name__}).", file=sys.stderr) return 1 except ValueError: print("API returned invalid JSON.", file=sys.stderr) return 1 if __name__ == "__main__": raise SystemExit(main())