"""Submit your model's outputs to SKYBENCH using Python's standard library.
Set SKYBENCH_URL and SKYBENCH_API_KEY. Provide a JSON file:
{"entryId":"...","forecasts":[{"taskId":"...","prediction":18.4}]}
Use your own model outputs. The sample value only illustrates the format.
"""
import json
import os
import sys
import urllib.error
import urllib.request

def main():
    if len(sys.argv) != 2:
        raise SystemExit("Usage: python submit-forecasts.py predictions.json")
    base = os.environ["SKYBENCH_URL"].rstrip("/")
    key = os.environ["SKYBENCH_API_KEY"]
    with open(sys.argv[1], encoding="utf-8") as file:
        payload = json.load(file)
    data = json.dumps(payload).encode()
    if len(data) > 32768:
        raise SystemExit("Batch exceeds 32 KB. Split it before submitting.")
    request = urllib.request.Request(
        base + "/api/league/forecasts", data=data,
        headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"},
        method="POST",
    )
    try:
        with urllib.request.urlopen(request, timeout=30) as response:
            result = json.load(response)
    except urllib.error.HTTPError as error:
        print(error.read().decode(), file=sys.stderr)
        raise SystemExit(1)
    print(json.dumps(result, indent=2))
    # Exact retries are idempotent. Never change a sealed value when retrying.
    if any(item["status"] == "error" for item in result["results"]):
        raise SystemExit(2)

if __name__ == "__main__":
    main()

