"""Dependency-free Share API client for server-side app credentials."""
import base64
import hashlib
import hmac
import json
import time
import urllib.error
import urllib.parse
import urllib.request

class ShareError(Exception):
    def __init__(self, code, status, request_id=None):
        super().__init__(code)
        self.code, self.status, self.request_id = code, status, request_id

class ShareClient:
    def __init__(self, token, base='https://share.inklura.fr'):
        url = urllib.parse.urlsplit(base)
        if url.scheme != 'https' or url.username or url.password or url.path not in ('', '/') or url.query or url.fragment:
            raise ValueError('Expected HTTPS origin')
        self.token, self.base = token, base.rstrip('/')
        class NoRedirect(urllib.request.HTTPRedirectHandler):
            def redirect_request(self, *args, **kwargs):
                return None
        self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), NoRedirect())

    def call(self, section, **body):
        if section not in ('artifacts', 'jobs', 'events'):
            raise ValueError('Unknown API section')
        replayable = body.get('action') in ('list', 'get', 'read', 'chunk', 'commit') or body.get('action') in ('begin', 'submit') and bool(body.get('idempotency_key'))
        for attempt in range(3):
            req = urllib.request.Request(self.base+'/api/v1/'+section, data=json.dumps(body).encode(), headers={'Authorization':'Bearer '+self.token,'Content-Type':'application/json','User-Agent':'SharePythonSDK/1.0'})
            try:
                with self.opener.open(req, timeout=60) as response:
                    return json.load(response)
            except urllib.error.HTTPError as error:
                try:
                    detail=json.loads(error.read(4096)).get('error', {})
                except ValueError:
                    detail={}
                if not isinstance(detail, dict):
                    detail={}
                if not replayable or attempt==2 or error.code not in (429,500,502,503,504):
                    raise ShareError(detail.get('code','request_failed'),error.code,detail.get('request_id')) from None
            except urllib.error.URLError:
                if not replayable or attempt==2:
                    raise ShareError('transport_failed',0) from None
            time.sleep(.5*2**attempt)

    def publish(self, files, *, project, idempotency_key, title='Report', artifact_id=None, revision=None, entry=None, trace_id=None):
        """files: list of {path, content: bytes, type?: MIME}; updates require revision."""
        manifest=[{'path':f['path'],'bytes':len(f['content']),'type':f.get('type','application/octet-stream')} for f in files]
        draft=self.call('artifacts',action='begin',project=project,idempotency_key=idempotency_key,title=title,id=artifact_id,revision=revision,entry=entry,trace_id=trace_id,files=manifest)
        if not draft.get('committed'):
            for f in files:
                for index,offset in enumerate(range(0,len(f['content']),draft['chunk_bytes'])):
                    text=base64.b64encode(f['content'][offset:offset+draft['chunk_bytes']]).decode()
                    self.call('artifacts',action='chunk',draft_id=draft['draft_id'],path=f['path'],index=index,content_base64='\n'.join(text[n:n+6] for n in range(0,len(text),6)))
        return self.call('artifacts',action='commit',draft_id=draft['draft_id'])

    def request_revision(self, **request):
        return self.call('jobs',action='submit',**request)['job']

    def get_job(self, job_id):
        return self.call('jobs',action='get',id=job_id)['job']

    def read_file(self, artifact_id, version, path):
        artifact=self.call('artifacts',action='get',id=artifact_id)['artifact']
        file=next(f for v in artifact['versions'] if v['number']==version for f in v['files'] if f['path']==path)
        output=bytearray()
        for index in range(file['chunks']):
            c=self.call('artifacts',action='read',id=artifact_id,version=version,path=path,index=index)
            part=base64.b64decode(c['content_base64'],validate=True)
            if len(part)!=c['bytes'] or hashlib.sha256(part).hexdigest()!=c['sha256']:
                raise ValueError('chunk_integrity_failed')
            output.extend(part)
        if len(output)!=file['bytes']:
            raise ValueError('incomplete_file')
        return bytes(output)


def verify_share_event(secret, raw, timestamp, signature, now=None):
    """Verify before JSON parsing. Persist event IDs so repeated delivery is harmless."""
    try:
        if not timestamp.isdecimal() or len(timestamp)>12 or abs((time.time() if now is None else now)-int(timestamp))>300:
            return False
        expected='v1='+hmac.new(secret.encode(),timestamp.encode()+b'.'+raw,hashlib.sha256).hexdigest()
        return hmac.compare_digest(expected,signature)
    except (TypeError,ValueError,AttributeError):
        return False
