import sys,json
ROOT=globals().get('TVV_ROOT','')
if ROOT not in sys.path:sys.path.insert(0,ROOT)
from run_record import start,finish,sha,save_json
from map_processing import process
paths=globals().get('TVV_MAP_RUNS',[])
if not paths:raise ValueError('Задайте TVV_MAP_RUNS: все части карты')
folder,record=start(ROOT,globals().get('TVV_OUTPUT_ROOT',ROOT+'/runs'),'map-processing',['run_map_processing.py','map_processing.py','energy_map.py','numerics.py','run_record.py'],'independent map controls, angular averaging, reciprocity and energy')
rows=[];reference=None;sources=[]
try:
    for path in paths:
        with open(path+'/receipt.json') as f:receipt=json.loads(f.read())
        if receipt['status']!='passed_map_field_points_not_interpolation_validation':raise ValueError('Незавершённая полевая часть карты')
        for prefix,files in [('/snapshot/',receipt['inputs_and_programs']),('/',receipt['outputs'])]:
            for name,expected in files.items():
                if sha(path+prefix+name)!=expected:raise ValueError('Не совпал SHA-256: '+name)
        if reference is not None and receipt['inputs_and_programs']!=reference:raise ValueError('Разные входы/программы частей карты')
        reference=receipt['inputs_and_programs']
        with open(path+'/results.json') as f:rows.extend(json.loads(f.read()))
        with open(path+'/snapshot/magnetic-map-plan.json') as f:plan=json.loads(f.read())
        sources.append({'path':path,'receipt_sha256':sha(path+'/receipt.json')})
    interpolation=globals().get('TVV_MAP_INTERPOLATION','component-trilinear')
    if interpolation=='coenergy-tricubic-hermite':
        rejected=process(plan,rows,'component-trilinear');rejected['sources']=sources
        save_json(folder+'/component-trilinear-check.json',rejected)
    result=process(plan,rows,interpolation);result['sources']=sources;save_json(folder+'/magnetic-map.json',result)
    record['sources']=sources
    if not result['validated']:raise ValueError('Контроль карты не пройден: требуется сгущение, критерии не изменять')
    finish(folder,record,'passed_independent_map_validation')
except Exception as error:record['error']=str(error);finish(folder,record,'failed');raise
print('TVV_MAP_PROCESSING',folder)
