import sys
import os
repo = os.path.dirname(__file__)
# Asegurar rutas de imports
sys.path.insert(0, os.path.join(repo, 'veny', 'src'))
from quantum_fs import DedupFS
from module_utils import prepare_mountpoint

mp = os.path.join(repo, 'test_mount')
print('Preparing mountpoint:', mp)
if not prepare_mountpoint(mp):
    raise SystemExit('Failed to prepare mountpoint')

fs = DedupFS(mp)

# Test write + read
original = (b"Hello Quantum World!\n" * 100)[:5000]
print('Writing data length', len(original))
written = fs.write('file1.txt', original, 0, None)
print('write returned', written)
readback = fs.read('file1.txt', 10000, 0, None)
print('readback length', len(readback))
assert readback == original, 'Read data does not match original'
print('Write/Read OK')

# Test compact/maintenance
fs.compact_global_index()
fs.garbage_collect_orphans()
fs.rebuild_merkle_tree()
print('Maintenance functions executed')

# Test snapshot/restore
fs.snapshot('snap1')
fs.write('file2.txt', b'abc'*1000, 0, None)
if 'file2.txt' in fs.files:
    print('file2 created')
fs.restore_snapshot('snap1')
if 'file2.txt' not in fs.files:
    print('Snapshot restore OK')
else:
    print('Snapshot restore failed')

# New MPS roundtrip test: ensure each QuantumFigure has MPS and it reconstructs exactly
for bh, qf in fs.quantum_figures.items():
    if bh == 'global_index':
        continue
    if hasattr(qf, 'mps') and qf.mps:
        from mps_utils import tt_reconstruct
        reconstructed = tt_reconstruct(qf.mps)
        orig = qf.data
        if reconstructed != orig:
            print(f'ERROR: MPS roundtrip failed for block {bh}')
            raise SystemExit('MPS roundtrip mismatch')
print('MPS roundtrip tests passed')

# Now test fusion (merge) operation and verify integrity
# Save original reconstruction per file (use fs.read to be consistent with compacted_index mode)
original_contents = {}
for path in list(fs.files.keys()):
    original_contents[path] = fs.read(path, 10**9, 0, None)

fs.superpose_similar_quantum_figures(precision=1)
# After merging, ensure all files still reconstruct correctly
for path in list(fs.files.keys()):
    reconstructed = fs.read(path, 10**9, 0, None)
    original = original_contents.get(path, b"")
    if reconstructed != original:
        print(f'ERROR: After merge, reconstruction mismatch for {path}')
        print('Original length:', len(original))
        print('Reconstructed length:', len(reconstructed))
        raise SystemExit('Merge reconstruction mismatch')
print('Merge integrity test passed')

# Test clear_mountpoint on real filesystem (create a file then clear)
with open(os.path.join(mp, 'tempfile.txt'), 'wb') as f:
    f.write(b'temp')
print('Temp file created on mountpoint')
fs.clear_mountpoint()
files_left = list(os.listdir(mp))
print('Files left in mountpoint after clear:', files_left)
assert len(files_left) == 0, 'Mountpoint not empty after clear_mountpoint'
print('clear_mountpoint OK')

print('ALL LOCAL TESTS PASSED')
