import sys, os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'veny', 'src'))
from quantum_fs import DedupFS
from module_utils import prepare_mountpoint
repo = os.path.dirname(__file__)
mp = os.path.join(repo, 'test_mount')
prepare_mountpoint(mp)
fs = DedupFS(mp)
# write same data as run_local_tests
original = (b"Hello Quantum World!\n" * 100)[:5000]
fs.write('file1.txt', original, 0, None)
fs.compact_global_index()
# add another file to create multiple blocks
fs.write('file2.txt', b'abc'*1000, 0, None)
print('Files and blocks BEFORE merge:')
for fname, fentry in fs.files.items():
    print(fname, 'blocks:', fentry.get('blocks'))
print('\nData blocks sizes:')
for h, data in fs.data_blocks.items():
    print(h, len(data))
# call merge
fs.superpose_similar_quantum_figures(precision=1)
print('\nFiles and blocks AFTER merge:')
for fname, fentry in fs.files.items():
    print(fname, 'blocks:', fentry.get('blocks'))
print('\nData blocks sizes AFTER:')
for h, data in fs.data_blocks.items():
    print(h, len(data))
# Try reconstruct file1
r = fs.read('file1.txt', 10**9, 0, None)
print('\nRead len file1:', len(r))
# compute original from data_blocks
orig = b"".join(fs.data_blocks[bh] for bh in fs.files['file1.txt']['blocks'])
print('Orig from data_blocks len:', len(orig))
if r != orig:
    print('Mismatch detected')
    for i in range(min(len(r), len(orig))):
        if r[i] != orig[i]:
            print('First diff at', i)
            print('r[:40]:', r[:40])
            print('orig[:40]:', orig[:40])
            break
else:
    print('OK: reconstruct equals concat of data_blocks')
