# Выполняется только встроенным Python FEMM 5.
# Распакуйте весь ZIP в новую папку и запустите этот файл через меню Scripts.
# Запускайте сохранённый файл целиком: путь передаётся в sys.argv[0].
import os, sys, json, math, hashlib
assert sys.implementation.name == 'micropython', 'Нужен встроенный Python FEMM 5'
_saved_file = globals().get('__file__') or (sys.argv[0] if sys.argv else '')
assert _saved_file and os.path.isfile(_saved_file), 'Запустите сохранённый файл из полного распакованного комплекта'
os.chdir(os.path.dirname(os.path.abspath(_saved_file)))
with open('manifest.json') as f: manifest = json.load(f)

def digest(path):
    h = hashlib.sha256()
    with open(path, 'rb') as f:
        while True:
            b = f.read(65536)
            if not b: break
            h.update(b)
    return ''.join('%02x' % b for b in h.digest())

# До расчёта проверяем переносимость и неизменность всех приложенных входов.
for item in manifest['files']:
    assert digest(item['path']) == item['sha256'], 'Изменён вход ' + item['path']
with open('expected-native.json') as f: cases = json.load(f)
os.mkdir('reproduced')   # Отказ от перезаписи предыдущего результата намеренный.
out = {'implementation': str(sys.implementation), 'runtime': sys.version,
       'case_id': manifest['case_id'], 'fresh_fields': [], 'checks': []}

def z(v):
    if isinstance(v, dict): return complex(v['re'], v['im'])
    if isinstance(v, (list, tuple)): return complex(v[0], v[1])
    return complex(v)

def serial(v):
    if isinstance(v, complex): return [v.real, v.imag]
    if isinstance(v, (list, tuple)): return [serial(t) for t in v]
    if isinstance(v, dict): return {k: serial(t) for k,t in v.items()}
    return v

def check(label, actual, expected, tolerance):
    error = abs(z(actual) - z(expected))
    out['checks'].append({'name':label,'actual':serial(actual),
                         'expected':serial(expected),'error':error,
                         'tolerance':tolerance,'passed':error <= tolerance})

for j, spec in enumerate(cases):
    for cmd in ('mo_close', 'mi_close'):
        try: globals()[cmd]()
        except Exception: pass
    opendocument(spec['model'])
    mi_saveas('reproduced/control-' + str(j) + '.fem')
    if 'frequency_Hz' in spec:
        mi_probdef(spec['frequency_Hz'], 'millimeters', 'planar', 1e-8,
                   spec.get('depth_mm',100), 20)
    for name,value in spec.get('set_circuits',{}).items():
        mi_modifycircprop(name, 1, z(value))
    if spec.get('rotate_deg'):
        mi_selectgroup(2); mi_moverotate(0,0,spec['rotate_deg'],4); mi_clearselected()
    if 'boundary' in spec:
        name,index,value = spec['boundary']; mi_modifyboundprop(name,index,value)
    mi_saveas('reproduced/control-' + str(j) + '.fem')
    mi_analyze(1); mi_loadsolution(); mo_smooth('off')
    row = {'model':spec['model'],'elements':mo_numelements(),'nodes':mo_numnodes(),
           'problem':serial(mo_getprobleminfo()),'circuits':{}}
    for name, values in spec.get('circuits',{}).items():
        actual = list(mo_getcircuitproperties(name)); row['circuits'][name] = serial(actual)
        for k,expected in enumerate(values):
            check('Поле '+str(j)+' '+name+' '+('I','U','Psi')[k], actual[k], expected,
                  max(1e-9, 1e-5*abs(z(expected))))
    mo_clearblock(); mo_groupselectblock()
    for key,expected in spec.get('integrals',{}).items():
        actual=mo_blockintegral(int(key)); row['integral_'+key]=serial(actual)
        check('Объёмный интеграл '+key,actual,expected,max(1e-7,1e-5*abs(z(expected))))
    mo_clearblock()
    if 'gap_torque' in spec:
        q=spec['gap_torque']; actual=mo_gapintegral(q['name'],0)
        if isinstance(actual,(list,tuple)): actual=actual[0]
        row['gap_torque_Nm']=serial(actual)
        check('Момент границы AGE',actual,q['expected'],q['tolerance'])
    if 'torque' in spec:
        q=spec['torque'];mo_groupselectblock(q['group']);actual=mo_blockintegral(22);mo_clearblock()
        row['torque_Nm']=serial(actual);check('Момент WST',actual,q['expected'],q['tolerance'])
    if 'magnet_probe' in spec:
        # Исходные графические минимумы получены со сглаживанием поля.
        # Настройку сохраняем явно, чтобы сравнивать одинаковые величины.
        mo_smooth('on')
        q=spec['magnet_probe']
        for p in q['extrema']:
            x,y=p['minimum_point_mm'];angle=math.atan2(y,x)
            sign=1 if p['pole']%2==0 else -1;v=mo_getpointvalues(x,y)
            h=(z(v[1]).real*sign*math.cos(angle)+z(v[2]).real*sign*math.sin(angle)-q['Br_T'])/(4*math.pi*1e-7*q['mu'])
            check('Физический H вдоль намагничивания полюса '+str(p['pole']),h,p['Hparallel_min_A_m'],.02)
    out['fresh_fields'].append(row)
    with open('reproduced/native-result.json','w') as f: json.dump(out,f)
    mo_close();mi_close()

# Повторяем предметные арифметические проверки сохранённых серий.
with open('postprocess.py') as f: exec(f.read(),globals())
out['passed']=all(q['passed'] for q in out['checks'])
with open('reproduced/native-result.json','w') as f: json.dump(out,f)
print('AUDIT_CASE',out['case_id'],'FIELDS',len(out['fresh_fields']),
      'CHECKS',len(out['checks']),'PASSED',out['passed'])
assert out['passed'], 'Есть несогласованные численные проверки; см. native-result.json'
