"""
OpenRouter 429 重试模板（Python）
- 捕获 429 -> 指数退避（带抖动）-> 最大重试次数 -> 绝不无限重试 -> 最终失败明确提示
- 尊重响应头 Retry-After；否则指数退避，上限 30s
- 把下面 YOUR_OPENROUTER_API_KEY 换成你自己的 Key（不要硬编码进版本库）
"""
import time
import random
import requests

API_URL = "https://openrouter.ai/api/v1/chat/completions"
API_KEY = "YOUR_OPENROUTER_API_KEY"  # 替换为你自己的 OpenRouter API Key


def call_openrouter(messages, model="openrouter/auto", max_retries=5):
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json",
    }
    payload = {"model": model, "messages": messages}

    backoff = 1.0  # 秒
    for attempt in range(1, max_retries + 1):
        resp = requests.post(API_URL, headers=headers, json=payload, timeout=30)

        # 非 429 直接按正常逻辑处理（成功返回 / 其他错误抛出）
        if resp.status_code != 429:
            resp.raise_for_status()
            return resp.json()

        # 429：尊重 Retry-After，否则指数退避（带抖动），上限 30s
        ra = resp.headers.get("Retry-After")
        wait = int(ra) if (ra and ra.isdigit()) else backoff
        wait += random.uniform(0, 0.5)
        print(f"[429] 第 {attempt}/{max_retries} 次，{wait:.1f}s 后重试")
        time.sleep(wait)
        backoff = min(backoff * 2, 30)

    # 绝不无限重试：达到上限就明确失败
    raise RuntimeError("已重试 max_retries 次仍收到 429，请稍后或换模型/充值")


if __name__ == "__main__":
    try:
        data = call_openrouter([{"role": "user", "content": "你好"}])
        print(data["choices"][0]["message"]["content"])
    except RuntimeError as e:
        print("最终失败：", e)
