"""Local-only retry demonstration; requires the openai Python package."""
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import httpx
from openai import OpenAI, RateLimitError

class MockAPI(BaseHTTPRequestHandler):
    attempts = 0
    fail_first = 0
    def log_message(self, *args):
        pass
    def do_GET(self):
        type(self).attempts += 1
        if type(self).attempts <= type(self).fail_first:
            status, payload = 429, {"error": {"message": "local test rate limit", "type": "rate_limit_error"}}
        else:
            status, payload = 200, {"object": "list", "data": []}
        body = json.dumps(payload).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Retry-After", "0.01")
        self.end_headers()
        self.wfile.write(body)

server = ThreadingHTTPServer(("127.0.0.1", 0), MockAPI)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
    for retries, fail_first, expected_attempts, expected_result in [(0, 1, 1, "rate limit"), (2, 1, 2, "success"), (2, 10, 3, "rate limit")]:
        MockAPI.attempts, MockAPI.fail_first = 0, fail_first
        with OpenAI(api_key="local-test-only", base_url=f"http://127.0.0.1:{server.server_port}/v1", max_retries=retries, timeout=3, http_client=httpx.Client(trust_env=False)) as client:
            try:
                client.models.list()
                result = "success"
            except RateLimitError:
                result = "rate limit"
        assert (MockAPI.attempts, result) == (expected_attempts, expected_result)
        print(f"max_retries={retries}; requests={MockAPI.attempts}; result={result}")
finally:
    server.shutdown()
    server.server_close()
    thread.join(timeout=5)
