"""A fallback chain over two local mock vendors: `naive` stops on 402, `owners` moves on.
Usage: python3 chain.py naive | python3 chain.py owners (no network, no keys)."""
import http.server, json, sys, threading, urllib.error, urllib.request

def mock(port, status, body):
    class H(http.server.BaseHTTPRequestHandler):
        def do_POST(self):
            self.rfile.read(int(self.headers.get("Content-Length", 0)))
            self.send_response(status)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
            self.wfile.write(json.dumps(body).encode())
        def log_message(self, *a):
            pass
    srv = http.server.HTTPServer(("127.0.0.1", port), H)
    threading.Thread(target=srv.serve_forever, daemon=True).start()

mock(8401, 402, {"error": {"type": "billing_error", "message": "credit balance too low"}})
mock(8402, 200, {"model": "vendor-b-model", "text": "Here is your summary."})
CHAIN = [("vendor-a", "http://127.0.0.1:8401"), ("vendor-b", "http://127.0.0.1:8402")]

def call(url):
    req = urllib.request.Request(url, data=b'{"prompt":"summarize"}', method="POST")
    try:
        with urllib.request.urlopen(req) as r:
            return r.status, json.load(r)
    except urllib.error.HTTPError as e:
        return e.code, json.load(e)

def naive(status):
    # The classic two buckets: 429, 5xx move on; every other 4xx is the caller's fault.
    return "next" if status == 429 or status >= 500 else "stop"

def owners(status):
    if status in (401, 402, 403):
        return "next:account"  # the request was fine; another vendor could answer it
    if status == 429 or status >= 500:
        return "next:vendor"
    return "stop"  # 400, 413, 422: another vendor would reject it too

classify = naive if sys.argv[1:] == ["naive"] else owners
for name, url in CHAIN:
    status, body = call(url)
    if status == 200:
        print(f"200  {name}: {body['text']}  (answered by {body['model']})")
        break
    decision = classify(status)
    print(f"{status}  {name}: {body['error']['type']} -> {decision}")
    if decision.startswith("next:account"):
        print("     ALERT billing/auth problem at", name, "- someone should look at the card")
    if decision == "stop":
        print("     chain ended: the user gets an error")
        break
