from pathlib import Path
import base64,hashlib,json,sys,xml.etree.ElementTree as ET
p=Path(__file__).parent
fixtures={'windows-1252.xml':'<?xml version="1.0" encoding="windows-1252"?><label>café</label>'.encode('cp1252'),'utf-8.xml':'<?xml version="1.0" encoding="utf-8"?><label>café</label>'.encode('utf8'),'no-declaration.xml':'<label>café</label>'.encode('cp1252'),'mislabeled.xml':'<?xml version="1.0" encoding="UTF-8"?><label>café</label>'.encode('cp1252')}
def attempt(fn):
 try:return {'ok':True,'text':fn()}
 except Exception as e:return {'ok':False,'error_type':type(e).__name__,'error':str(e)}
rows=[]
for name,raw in fixtures.items():
 (p/name).write_bytes(raw);b64=base64.b64encode(raw);(p/(name+'.b64.txt')).write_bytes(b64);restored=base64.b64decode(b64,validate=True)
 row={'file':name,'bytes':len(raw),'base64_characters':len(b64),'sha256':hashlib.sha256(raw).hexdigest(),'roundtrip_equal':restored==raw,'source_hex':raw.hex(),'byte_parse':attempt(lambda:ET.fromstring(restored).text),'forced_utf8':attempt(lambda:ET.fromstring(restored.decode('utf8')).text),'latin1_then_parse':attempt(lambda:ET.fromstring(restored.decode('latin1')).text)};rows.append(row)
result={'python':sys.version.split()[0],'elementtree':ET.VERSION,'fixtures':rows}
(p/'raw-output.json').write_text(json.dumps(result,ensure_ascii=True,indent=2),encoding='utf8');print(json.dumps(result,ensure_ascii=True,indent=2))

