"""Bounded, thread-local persistent HTTP connections for read-only acceptance."""
import threading
import time
from urllib.parse import urlsplit

import requests


class ReadOnlyHTTP:
    def __init__(self,base,attempts=5):
        parsed=urlsplit(base)
        if parsed.scheme not in ('http','https') or not parsed.netloc or parsed.username or parsed.password or parsed.path not in ('','/') or parsed.query or parsed.fragment:
            raise ValueError('Expected an explicit public/local service origin without credentials')
        if type(attempts) is not int or not 1<=attempts<=5:raise ValueError('Bounded retry count required')
        self.base=base.rstrip('/');self.attempts=attempts;self.local=threading.local()
        self.lock=threading.Lock();self.sessions=[];self.cookies=requests.cookies.RequestsCookieJar();self.retries=[]

    def session(self):
        if not hasattr(self.local,'session'):
            session=requests.Session()
            with self.lock:
                session.cookies.update(self.cookies);self.sessions.append(session)
            self.local.session=session
        return self.local.session

    def request(self,path,*,method='GET',data=None,expected=200):
        parsed=urlsplit(path)
        if not path.startswith('/') or path.startswith('//') or parsed.netloc or parsed.scheme or parsed.fragment:
            raise ValueError('Expected a same-origin relative service route')
        if method not in ('GET','HEAD') and not (method=='POST' and parsed.path in ('/api/login','/api/review/login') and not parsed.query and
                isinstance(data,dict) and set(data)=={'key'} and isinstance(data['key'],str)):
            raise ValueError('Acceptance may not submit annotations or object mutations')
        if method in ('GET','HEAD') and data is not None:raise ValueError('Read-only requests must not send a body')
        headers={'X-Review-Request':'1'} if method=='POST' else {}
        for attempt in range(1,self.attempts+1):
            try:
                response=self.session().request(method,self.base+path,json=data,headers=headers,timeout=(20,90),allow_redirects=False)
                raw=response.content
            except requests.RequestException as error:
                kind=type(error).__name__
                if attempt==self.attempts:raise ValueError('Public transport failed after bounded retries: '+kind+' '+path) from None
            else:
                if response.status_code==expected:return response
                if response.status_code not in (502,503,504):
                    raise ValueError('Unexpected public HTTP status '+str(response.status_code)+' for '+path)
                kind='HTTP '+str(response.status_code)
                if attempt==self.attempts:raise ValueError('Public transport failed after bounded retries: '+kind+' '+path)
            with self.lock:self.retries.append(dict(route=path,attempt=attempt,error=kind))
            time.sleep(.5*attempt)

    def get(self,path,*,expected=200):return self.request(path,expected=expected)

    def login(self,key,*,gallery=False):
        response=self.request('/api/review/login' if gallery else '/api/login',method='POST',data=dict(key=key))
        with self.lock:self.cookies.update(response.cookies)
        return response

    def close(self):
        for session in self.sessions:session.close()

    def __enter__(self):return self
    def __exit__(self,*_):self.close()
