"""Decode named computation artifacts from stdin into the current directory.

  sage -python check_lattice.py | python3 decode_artifacts.py
  sage -python compute.py | python3 decode_artifacts.py

No account or website access is required. Ordinary progress goes to stdout.
"""
from pathlib import Path
import sys,base64,re
for line in sys.stdin:
    if line.startswith('ARTIFACT '):
        _,name,data=line.rstrip().split(' ',2)
        if not re.fullmatch(r'[A-Za-z0-9_][A-Za-z0-9_.-]*',name):
            raise ValueError('Unsafe artifact name')
        content=base64.b64decode(data,validate=True)
        Path(name).write_bytes(content)
        print('saved',name,len(content),'bytes')
    else:print(line,end='')
