# Rotate an endpoint's signing secret. The old one keeps signing for GRACE_HOURS (0 retires every older secret now). Python 3.9+ with requests.
import os
import sys

import requests

base = os.environ.get("RELATIONSAI_API_BASE", "https://voice-api.relationsai.com/v1")
endpoint_id = os.environ.get("WEBHOOK_ENDPOINT_ID") or sys.exit("Set WEBHOOK_ENDPOINT_ID to an endpoint id (we_...)")
grace_hours = int(os.environ.get("GRACE_HOURS", "24"))  # 0, 1, 24 or 168

r = requests.post(
    f"{base}/webhook-endpoints/{endpoint_id}/rotate-secret",
    headers={
        "Authorization": f"Bearer {os.environ['RELATIONSAI_API_KEY']}",
    },
    json={"grace_period_hours": grace_hours},
    timeout=30,
)
endpoint = r.json()
if not r.ok:
    err = endpoint["error"]
    sys.exit(f"{err['code']}: {err['message']} (request {err['request_id']})")
print(f"New secret for {endpoint['id']} (shown once): {endpoint['secret']}")
print(f"Deploy it before the grace period ({grace_hours} h) ends; until then deliveries carry both signatures.")
