"""Standard-library example client. Keep secrets in server-side environment variables."""
import hashlib,hmac,json,secrets,time,re,urllib.request
from urllib.parse import urlsplit

class NoRedirects(urllib.request.HTTPRedirectHandler):
    def redirect_request(self,*args,**kwargs):return None

class DistributionClient:
    def __init__(self,base_url,app_id,secret,timeout=10):
        parsed=urlsplit(base_url)
        if parsed.scheme!='https' and not (parsed.scheme=='http' and parsed.hostname in ('localhost','127.0.0.1','::1')):
            raise ValueError('Use HTTPS, except for local development')
        if parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path not in ('','/'):
            raise ValueError('base_url must contain only scheme, host and optional port')
        self.base_url=base_url.rstrip('/');self.app_id=app_id;self.secret=secret;self.timeout=timeout
        self.opener=urllib.request.build_opener(NoRedirects())
    def request(self,method,path,payload=None):
        if not path.startswith('/api/v1/distribution-api/v1/') or '?' in path or '#' in path:raise ValueError('Use a distribution API path without query or fragment')
        if method.upper()=='GET' and payload is not None:raise ValueError('GET requests cannot contain a body')
        body=b'' if payload is None else json.dumps(payload,ensure_ascii=False,separators=(',',':')).encode()
        timestamp=str(int(time.time()));nonce=secrets.token_hex(16)
        message='\n'.join((method.upper(),path,timestamp,nonce,hashlib.sha256(body).hexdigest()))
        signature=hmac.new(self.secret.encode(),message.encode(),hashlib.sha256).hexdigest()
        headers={'X-App-Id':self.app_id,'X-Timestamp':timestamp,'X-Nonce':nonce,'X-Signature':signature,'Content-Type':'application/json'}
        request=urllib.request.Request(self.base_url+path,data=body if method.upper()!='GET' else None,headers=headers,method=method.upper())
        with self.opener.open(request,timeout=self.timeout) as response:return json.load(response)
    def catalog(self):
        return self.request('GET','/api/v1/distribution-api/v1/wallet/catalog')
    def wallet_batch_issue(self,plan_code,max_unit_price,items):
        return self.request('POST','/api/v1/distribution-api/v1/wallet/batch-issue',{'plan_code':plan_code,'max_unit_price':max_unit_price,'items':items})
    def wallet_phone_grant(self,plan_code,max_unit_price,phone,request_key):
        return self.request('POST','/api/v1/distribution-api/v1/wallet/phone-grant',{'plan_code':plan_code,'max_unit_price':max_unit_price,'phone':phone,'request_key':request_key})
    def balance(self):
        return self.request('GET','/api/v1/distribution-api/v1/wallet/balance')
    def wallet_issue(self,plan_code,max_unit_price,request_key,external_ref,source='manual'):
        return self.request('POST','/api/v1/distribution-api/v1/wallet/issue',{'plan_code':plan_code,'max_unit_price':max_unit_price,'request_key':request_key,'external_ref':external_ref,'source':source})
    def inventory(self,page=1,size=100):
        return self.request('POST','/api/v1/distribution-api/v1/inventory',{'page':page,'size':size})
    def issue(self,purchase_id,request_key,external_ref,source='manual'):
        return self.request('POST','/api/v1/distribution-api/v1/codes/issue',{'purchase_id':purchase_id,'request_key':request_key,'external_ref':external_ref,'source':source})
    def batch_issue(self,purchase_id,items):
        return self.request('POST','/api/v1/distribution-api/v1/codes/batch-issue',{'purchase_id':purchase_id,'items':items})
    def status(self,code_id=None,request_key=None):
        if bool(code_id)==bool(request_key):raise ValueError('Provide either code_id or request_key')
        return self.request('POST','/api/v1/distribution-api/v1/codes/status',{'id':code_id} if code_id else {'request_key':request_key})


def verify_webhook(secret,headers,body,current_timestamp=None):
    """Verify first, persist/deduplicate payload['id'] in the receiver before returning 2xx."""
    stamp=headers.get('X-Pailing-Timestamp','');event_id=headers.get('X-Pailing-Event-Id','');provided=headers.get('X-Pailing-Signature','')
    try:
        from uuid import UUID
        UUID(event_id)
        if abs((time.time() if current_timestamp is None else current_timestamp)-int(stamp))>300:raise ValueError()
    except (ValueError,TypeError):raise ValueError('Invalid webhook timestamp or event ID')
    message='\n'.join([stamp,event_id,hashlib.sha256(body).hexdigest()])
    expected=hmac.new(secret.encode(),message.encode(),hashlib.sha256).hexdigest()
    if not isinstance(provided,str) or not re.fullmatch(r'[0-9a-f]{64}',provided) or not hmac.compare_digest(expected,provided):raise ValueError('Invalid webhook signature')
    payload=json.loads(body)
    if not isinstance(payload,dict) or payload.get('id')!=event_id:raise ValueError('Webhook event ID mismatch')
    return payload
