"""Маленький журнал запуска для встроенного Python; копии входов неизменны."""
import os, json, hashlib, binascii


def sha(path):
    with open(path,'rb') as f:
        digest=hashlib.sha256()
        while True:
            chunk=f.read(65536)
            if not chunk:break
            digest.update(chunk)
    return binascii.hexlify(digest.digest()).decode()


def save_json(path,data):
    with open(path,'w') as f:f.write(json.dumps(data))


def start(root,parent,prefix,names,purpose):
    if not os.path.exists(parent):os.mkdir(parent)
    for n in range(1,100000):
        folder=parent+'/'+prefix+'-%05d'%n
        if not os.path.exists(folder):
            os.mkdir(folder);break
    else:raise ValueError('Исчерпаны имена запусков')
    os.mkdir(folder+'/snapshot')
    record={'schema':'tvv320-native-run-v2','status':'running','purpose':purpose,
            'inputs_and_programs':{},'outputs':{},'checks':{}}
    for name in names:
        if '/' in name or '\\' in name:raise ValueError('Нужны имена файлов комплекта')
        with open(root+'/'+name,'rb') as f:data=f.read()
        with open(folder+'/snapshot/'+name,'wb') as f:f.write(data)
        record['inputs_and_programs'][name]=sha(folder+'/snapshot/'+name)
    save_json(folder+'/receipt.json',record)
    return folder,record


def finish(folder,record,status):
    record['status']=status
    for name in os.listdir(folder):
        if name=='receipt.json' or name=='snapshot':continue
        record['outputs'][name]=sha(folder+'/'+name)
    save_json(folder+'/receipt.json',record)
