"""Verify the published excerpts, action comparison, test repair, and file integrity offline."""
import hashlib
import json
from pathlib import Path

root = Path(__file__).resolve().parent
read = lambda name: json.loads((root / name).read_text())
runs = read('recorded/runs.json')
assert [r['case'] for r in runs] == ['cold', 'warm', 'environment-change', 'restored', 'test-failure', 'test-fixed']
actions = {}
for run in runs:
    name = run['case']
    events = read('recorded/' + name + '.bep-excerpt.json')
    assert next(e['started']['uuid'] for e in events if 'started' in e) == run['invocationId']
    assert next(e['finished']['exitCode'].get('code', 0) for e in events if 'finished' in e) == run['exitCode']
    rows = read('recorded/' + name + '.actions.json')
    assert all(row['runner'] in ['remote', 'remote cache hit'] for row in rows)
    if name not in ['test-failure', 'test-fixed']:
        assert len(rows) == 1
        action = rows[0]
        assert action['mnemonic'] == 'PilotManifest' and action['exitCode'] == 0
        assert action['cacheHit'] == (name in ['warm', 'restored'])
        assert hashlib.sha256(run['output'].encode()).hexdigest() == run['outputSha256']
        assert action['actualOutputs'][0]['digest']['hash'] == run['outputSha256']
        actions[name] = action
    else:
        actual = sorted((e['id']['testResult']['run'], e['testResult']['status']) for e in events if 'testResult' in e)
        expected = [(1, 'PASSED'), (2, 'FAILED' if name == 'test-failure' else 'PASSED'), (3, 'PASSED')]
        assert actual == expected
        assert all(not e['testResult'].get('cachedLocally', False) for e in events if 'testResult' in e)
        # Bazel labels both test-setup and generate-xml actions TestRunner.
        # Reusing a test.xml generation result is not reusing the test itself.
        executions = [row for row in rows if row['commandArgs'][0].endswith('/test-setup.sh')]
        assert len(executions) == 3
        assert all(row['runner'] == 'remote' and row['cacheHit'] is False for row in executions)
        assert sorted(row['exitCode'] for row in executions) == ([0, 0, 1] if name == 'test-failure' else [0, 0, 0])
    print(name + ': recorded outcome and remote evidence verified')
base = actions['cold']
for name in ['warm', 'restored']:
    assert actions[name]['digest'] == base['digest']
for key in ['commandArgs', 'inputs', 'platform', 'listedOutputs']:
    assert actions['environment-change'].get(key) == base.get(key), key + ' changed unexpectedly'
assert base['environmentVariables'] == [{'name': 'PILOT_MODE', 'value': 'release'}]
assert actions['environment-change']['environmentVariables'] == [{'name': 'PILOT_MODE', 'value': 'debug'}]
assert actions['environment-change']['digest'] != base['digest']
miss = read('recorded/cache-event-excerpt.json')
assert miss['event']['missReason'] == 'ENV_CHANGED'
assert miss['event']['actionId'] == actions['environment-change']['digest']['hash']
assert miss['previousHit']['digestHash'] == base['digest']['hash']
for field in ['inputRootDigest', 'outputPathsHash', 'platformHash']:
    assert miss['event'][field] == miss['previousHit'][field]
assert miss['event']['environmentHash'] != miss['previousHit']['environmentHash']
comparison = read('recorded/configuration-comparison-excerpt.json')
assert comparison['effectiveOptions']['comparisonComplete'] is True
assert comparison['effectiveOptions']['addedFlags'][0]['values'] == ['PILOT_MODE=debug']
assert comparison['baseline']['remoteCacheHits'] == comparison['candidate']['remoteExecutions'] == 1
assert (root / 'BUILD.fixed.bazel').read_text() == (root / 'BUILD.bazel').read_text().replace('fail_run_two = True', 'fail_run_two = False')
count = 0
for line in (root / 'SHA256SUMS').read_text().splitlines():
    digest, name = line.split('  ', 1)
    path = (root / name).resolve()
    assert path.is_relative_to(root.resolve())
    assert hashlib.sha256(path.read_bytes()).hexdigest() == digest, name
    count += 1
print('PASS: four action/cache cases, six remote test runs, exact one-line repair, and ' + str(count) + ' checksums.')
