"""Authored byte fixtures with bounded explicit base64 policies."""
import base64,binascii,json,platform,re
def canonical(text,urlsafe=False):
 if not isinstance(text,str) or len(text)>128:raise ValueError('bounded ASCII text')
 alphabet=r'[A-Za-z0-9_-]*={0,2}' if urlsafe else r'[A-Za-z0-9+/]*={0,2}'
 if re.fullmatch(alphabet,text) is None:raise ValueError('alphabet policy')
 try:raw=base64.b64decode(text,altchars=b'-_' if urlsafe else None,validate=True)
 except (binascii.Error,ValueError) as e:raise ValueError('decoding') from e
 expected=(base64.urlsafe_b64encode(raw) if urlsafe else base64.b64encode(raw)).decode('ascii')
 if expected!=text:raise ValueError('noncanonical spelling')
 return raw
def demo():
 rows=[]
 for raw in [b'',b'a',b'ab',b'abc',bytes([251,255,0])]:
  a=base64.b64encode(raw).decode('ascii');u=base64.urlsafe_b64encode(raw).decode('ascii')
  assert len(a)==len(u)==4*((len(raw)+2)//3)
  assert canonical(a)==raw and canonical(u,True)==raw
  rows.append({'original_hex':raw.hex(),'bytes':len(raw),'standard':a,'urlsafe':u,'encoded_chars':len(a)})
 assert rows[-1]['standard']=='+/8A' and rows[-1]['urlsafe']=='-_8A'
 liberal=base64.b64decode('Y!Q==').hex();assert liberal=='61'
 try:base64.b64decode('Y!Q==',validate=True)
 except binascii.Error:strict_rejected=True
 else:raise AssertionError('nonalphabet accepted')
 assert base64.b64decode('YR==',validate=True)==b'a' and canonical('YQ==')==b'a'
 rejected=[]
 for label,value,url in [('nonalphabet','Y!Q==',False),('missing_padding','YQ',False),('nonzero_padbits','YR==',False),('wrong_url_alphabet','+/8A',True)]:
  try:canonical(value,url)
  except ValueError:rejected.append(label)
  else:raise AssertionError(label)
 return {'runtime':platform.python_version(),'rows':rows,'liberal_decode_nonalpha_hex':liberal,'validate_true_rejected_nonalpha':strict_rejected,'validate_true_noncanonical_padbits_decoded_hex':'61','canonical_policy_rejected':rejected,'scope':'Authored padded standard/URL-safe profiles; not encryption/compression/signature/Unicode codec. Other protocols may explicitly allow unpadded spelling.'}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=True,indent=2))
