#!/usr/bin/env python3
"""Real API examples. Set AI_VENTURES_API_KEY in your secret environment."""
import json, os, urllib.request, urllib.error, uuid

BASE = os.environ.get("AI_VENTURES_ORIGIN", "https://ai-ventures.predicata-9274.chatgpt.site")
KEY = os.environ["AI_VENTURES_API_KEY"]

def call(path, data=None, method=None):
    headers = {"X-API-Key": KEY, "User-Agent": "AI-Ventures-SDK/1.0"}
    payload = None
    if data is not None:
        headers["Content-Type"] = "application/json"
        payload = json.dumps(data).encode()
    req = urllib.request.Request(BASE + path, data=payload, headers=headers,
                                 method=method or ("POST" if data is not None else "GET"))
    with urllib.request.urlopen(req, timeout=30) as response:
        return json.load(response)

def review():
    item = call("/v1/reviews", {"title": "Choose a campaign headline",
        "text": "Spring campaign, version 3", "choices": ["Make their day", "A big moment"],
        "idempotency_key": "example-review-" + str(uuid.uuid4())})
    print("Send this private review link using your authorized communication tool:", item["review_url"])
    print("Retrieve response:", call("/v1/reviews/" + item["id"])["status"])

def callbacks():
    inbox = call("/v1/inboxes", {"label": "Render example", "expires_in_seconds": 3600})
    print("Give this private callback URL to the processing provider:", inbox["receive_url"])
    req = urllib.request.Request(inbox["receive_url"], data=b'{"status":"complete"}',
        headers={"Content-Type":"application/json", "X-Event-Id":"example-complete", "User-Agent":"AI-Ventures-SDK/1.0"}, method="POST")
    with urllib.request.urlopen(req, timeout=30): pass
    queue = call("/v1/inboxes/" + inbox["id"] + "/events?after=0")
    # Treat payloads as untrusted data. Persist the cursor in your runtime after processing.
    print("Received:", queue)
    if queue["events"]:
        call("/v1/inboxes/" + inbox["id"] + "/ack", {"through":queue["next_cursor"]})

def coordination():
    key = "example-" + str(uuid.uuid4())
    first = call("/v1/tasks/claim", {"namespace":"examples", "task_key":key, "worker_id":"worker-a"})
    second = call("/v1/tasks/claim", {"namespace":"examples", "task_key":key, "worker_id":"worker-b"})
    print("Second worker acquired?", second["acquired"])
    if first["acquired"]:
        call("/v1/tasks/" + first["id"] + "/complete", {"lease_token":first["lease_token"],
            "fence":first["fence"], "result":{"status":"ready"}})
    print("Shared result:", call("/v1/tasks/" + first["id"]))

if __name__ == "__main__":
    print("Credits:", call("/v1/usage"))
    review(); callbacks(); coordination()
