"""robot.py — make a picture with the Hugging Face image API.

Setup (one time):
    pip install requests
    Get a FREE token at https://huggingface.co/settings/tokens
    Save it as the HF_TOKEN environment variable:
        export HF_TOKEN="hf_your_real_token_here"          # Mac / Linux
        $env:HF_TOKEN = "hf_your_real_token_here"          # Windows PowerShell

Run it:
    python robot.py

Companion lesson: https://krueng.ai/apis.html
"""
import os
import requests

# 1. The ADDRESS (where). The KEY (who) is read from the env var HF_TOKEN.
API_URL = "https://router.huggingface.co/hf-inference/models/black-forest-labs/FLUX.1-schnell"
headers = {"Authorization": f"Bearer {os.environ['HF_TOKEN']}"}

# 2. Send a POST with the ORDER (body) — our picture idea
response = requests.post(
    API_URL,
    headers=headers,
    json={"inputs": "a friendly robot painting a colorful picture"},
)

# 3. If Hugging Face refused the request, SHOW the reason and stop —
#    don't write the error message into a file pretending to be a picture.
if not response.ok:
    print(f"Hugging Face rejected the request ({response.status_code}):")
    print(response.text)
    raise SystemExit(1)

# 4. The response IS the picture. Save the bytes to a file.
with open("robot.jpg", "wb") as file:
    file.write(response.content)

print("Done! Open robot.jpg to see your picture.")
