"""Verify exact profiled results with checked configuration and artifact destinations."""
import gzip
import hashlib
import json
from pathlib import Path

import yaml
from tools.benchmark_tum_window_processes import comparable

root = Path(__file__).resolve().parent
out = root / 'outputs/tum-small-process-profile-v1'
reference = root / 'outputs/tum-factor-preparation-suite-v1/01-current/result.json.gz'
reference_config = root / 'outputs/tum-factor-preparation-suite-v1/current/config.yaml'
sha = lambda p: hashlib.sha256(p.read_bytes()).hexdigest()
configs = [yaml.safe_load(p.read_bytes()) for p in (reference_config, out/'config.yaml')]
for config in configs:
    config['project']['output_dir'] = '<verified output destination>'
assert configs[0] == configs[1]
values = []
for result, path in ((json.loads(gzip.decompress(reference.read_bytes())), reference_config),
                     (json.loads((out/'result.json').read_bytes()), out/'config.yaml')):
    value = comparable(result)
    run = value['run']
    assert run['config_sha256'] == run['provenance']['config_sha256'] == sha(path)
    assert run['provenance']['command'] == ['calibrex', 'calibrate', str(path)]
    run['config_sha256'] = run['provenance']['config_sha256'] = '<verified output config>'
    run['provenance']['command'][2] = '<config>'
    destination = Path(yaml.safe_load(path.read_bytes())['project']['output_dir'])
    for key, relative in [('html_report', 'report.html'), ('rig_3d_viewer', 'artifacts/rig_3d.html')]:
        assert value['artifacts'][key] == str(destination / relative)
        value['artifacts'][key] = '<output>/' + relative
    values.append(value)
assert values[0] == values[1]
record = {
    'complete_result_exact_after_verified_output_path_normalization': True,
    'original_launcher_comparison': 'The original final assertion omitted two artifact destinations; all profile workers completed. This separate comparison verifies and normalizes only those destinations and their configuration fingerprints.',
    'provenance': {'auditor_sha256': sha(Path(__file__)),
                   'source_manifest_sha256': sha(out/'source/manifest.json'),
                   'profile_provenance_sha256': sha(out/'provenance.json'),
                   'result_sha256': sha(out/'result.json'), 'reference_result_sha256': sha(reference)},
}
(out/'comparison.json').write_text(json.dumps(record, indent=2)+'\n', encoding='utf-8')
print('All complete numerical results match; both artifact destinations verified and normalized.')
