"""Check API429 model-list membership; never send a generation request."""
import json
import os
import socket
import urllib.error
import urllib.request

URL = "https://gateway.api429.com/v1/models"
MAX_BYTES = 1024 * 1024
TIMEOUT_SECONDS = 15


class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def main():
    key = os.environ.get("API429_API_KEY", "").strip()
    model = os.environ.get("API429_MODEL", "").strip()
    if not key or not model:
        print("Set API429_API_KEY and API429_MODEL locally before running.")
        return 2
    if any(c in key for c in "\r\n"):
        print("Invalid credential format; check your local environment.")
        return 2
    request = urllib.request.Request(
        URL, headers={"Authorization": "Bearer " + key,
                      "Accept": "application/json"}, method="GET"
    )
    opener = urllib.request.build_opener(NoRedirect())
    try:
        with opener.open(request, timeout=TIMEOUT_SECONDS) as response:
            if response.status != 200:
                print("Unexpected HTTP status; stop and inspect locally.")
                return 1
            if response.headers.get_content_type() != "application/json":
                print("Expected JSON; stop and inspect locally.")
                return 1
            raw = response.read(MAX_BYTES + 1)
        if len(raw) > MAX_BYTES:
            print("Response exceeds the local size limit.")
            return 1
        payload = json.loads(raw)
        if (not isinstance(payload, dict) or "error" in payload
                or not isinstance(payload.get("data"), list)
                or not all(isinstance(row, dict)
                           and isinstance(row.get("id"), str)
                           for row in payload["data"])):
            print("Unexpected model-list structure; stop and inspect locally.")
            return 1
        if not any(row["id"] == model for row in payload["data"]):
            print("Exact model ID absent from this key's model list.")
            return 1
        print("Exact model ID found: model-list membership only; generation untested.")
        return 0
    except urllib.error.HTTPError as error:
        print("HTTP " + str(error.code) + "; no retry or redirect performed.")
    except (socket.timeout, TimeoutError):
        print("Request timed out; no automatic retry performed.")
    except urllib.error.URLError:
        print("Connection failed; no automatic retry performed.")
    except (ValueError, UnicodeError):
        print("Invalid JSON or local request format; stop and inspect locally.")
    return 1


if __name__ == "__main__":
    raise SystemExit(main())
