#!/usr/bin/env python3
"""Quattrino quickstart - INTENT -> AUTHORITY -> ACTION -> PROOF in one screen.

Prereq: an agent API key (run bootstrap_sandbox.py, or copy it from the web app).
  pip install nothing - the SDK is a single stdlib-only file:
  curl -o quattrino.py https://quattrino.io/api/v1/public/sdk/python
"""
import json, os
from quattrino import Quattrino          # ./quattrino.py (downloaded above)

cfg = json.load(open(".quattrino_sandbox.json")) if os.path.exists(".quattrino_sandbox.json") else {}
q = Quattrino(api_key=os.environ.get("QUATTRINO_AGENT_KEY") or cfg["api_key"],
              base_url=os.environ.get("QUATTRINO_BASE") or cfg.get("base", "https://quattrino.io"))

# 1. INTENT: the human said "buy the best USB-C cable under $20". Standing authority is $50.
#    The task NARROWS it to $20 - it can never widen it.
r = q.authorize(amount_minor=1999, merchant="Amazon", purpose="USB-C cable", commitment="ONE_TIME",
                task={"max_amount_minor": 2000})
print(r.decision, "effective max:", r.effective_maximum_minor, "set by:", r.binding_layer)   # AUTHORIZED 2000 task

# 2. Handle every answer the same way, every time:
def handle(r):
    if r.decision == "AUTHORIZED":         return "go"
    if r.decision == "DENIED":             return "stop: " + "; ".join(x["code"] for x in r.reasons)
    if r.decision == "APPROVAL_REQUIRED":  return "wait for the human: approval " + str((r.get("approval") or {}).get("approval_id"))
    if r.decision == "NEEDS_INFORMATION":  return "ask/declare: " + "; ".join(x["code"] for x in r.reasons)
print(handle(q.authorize(amount_minor=2001, merchant="Amazon", purpose="USB-C cable", commitment="ONE_TIME",
                         task={"max_amount_minor": 2000})))                                       # stop: exceeds_effective_authority

# 3. AUTHORITY -> ACTION: a BINDING authorization (single use, expires, revocable). You execute anywhere.
auth = q.authorize_binding(amount_minor=1999, merchant="Amazon", purpose="USB-C cable", commitment="ONE_TIME",
                           task={"max_amount_minor": 2000}, execution="external")
assert auth.authorized, auth.reasons
# ... your code buys the cable with your own provider ...

# 4. PROOF: record what actually happened; Quattrino compares it with the authorized terms.
out = q.record_outcome(auth.authorization_id, success=True, provider="amazon", provider_reference="114-2233",
                       actual_amount_minor=1999, commitment="ONE_TIME")
print(out["status"], out["compliance"]["status"])                                             # CONSUMED COMPLIANT
print(q.explain(auth.authorization_id)["plain_language"])
