"""Bounded transport retries for read-only service acceptance and login checks."""
import time
from urllib.error import HTTPError,URLError
from urllib.request import urlopen

RETRIES=[]


def open_checked(url,*,opener=None,timeout=90):
    method=url.get_method() if hasattr(url,'get_method') else 'GET'
    address=url.full_url if hasattr(url,'full_url') else url
    if method not in ('GET','HEAD') and not address.endswith(('/api/login','/api/review/login')):
        raise ValueError('Acceptance retries are not permitted for annotation writes')
    for attempt in range(5):
        try:return (opener.open if opener else urlopen)(url,timeout=timeout)
        except HTTPError as error:
            if error.code not in (502,503,504) or attempt==4:raise
            RETRIES.append(dict(url=address,attempt=attempt+1,error=f'HTTP {error.code}'))
        except (URLError,TimeoutError,ConnectionError) as error:
            if attempt==4:raise
            RETRIES.append(dict(url=address,attempt=attempt+1,error=type(error).__name__))
        time.sleep(.5*(attempt+1))
