#!/usr/bin/env python3
"""Call the Barg Sabz mock API with a token read from the environment — lesson AUT-201-L03.

The token is never printed, never put in the URL, and never written to logs.
Standard library only.

    # Linux/macOS
    export ORDERS_API_TOKEN=local-demo-token
    python call_with_env_token.py BS-1001
    # Windows PowerShell
    $env:ORDERS_API_TOKEN = "local-demo-token"
    python call_with_env_token.py BS-1001
"""
import json
import os
import sys
import urllib.error
import urllib.request

BASE = os.environ.get("ORDERS_API_BASE_URL", "http://127.0.0.1:8787")


def main(order_id):
    token = os.environ.get("ORDERS_API_TOKEN")
    if not token:
        sys.exit("ORDERS_API_TOKEN is not set; set it in your environment, not in this file")
    req = urllib.request.Request(f"{BASE}/orders/{order_id}", headers={"Authorization": f"Bearer {token}"})
    try:
        with urllib.request.urlopen(req, timeout=10) as r:
            print(r.status, json.dumps(json.load(r), ensure_ascii=False))
    except urllib.error.HTTPError as e:
        # log status and error code only; never the request headers
        body = json.load(e) if e.headers.get_content_type() == "application/json" else {}
        print(e.code, body.get("error", {}).get("code"), file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    if len(sys.argv) != 2:
        sys.exit("usage: python call_with_env_token.py ORDER_ID")
    main(sys.argv[1])
