#!/usr/bin/env python3
import zstandard as zstd
import sys

def aggressive_recover(filename):
    output_file = filename.replace('.zst', '')
    
    with open(filename, 'rb') as f:
        data = f.read()
    
    # Try different recovery strategies
    strategies = [
        lambda d: zstd.ZstdDecompressor().decompress(d),
        lambda d: zstd.ZstdDecompressor(max_window_size=2**31).decompress(d),
        lambda d: zstd.ZstdDecompressor().stream_reader(d).read(),
    ]
    
    for i, strategy in enumerate(strategies):
        try:
            result = strategy(data)
            with open(f"{output_file}.recovered{i}", 'wb') as out:
                out.write(result)
            print(f"Strategy {i} succeeded: {len(result)} bytes")
            return True
        except Exception as e:
            print(f"Strategy {i} failed: {e}")
    
    # Partial recovery - read until error
    try:
        dctx = zstd.ZstdDecompressor()
        with open(filename, 'rb') as f, open(f"{output_file}.partial", 'wb') as out:
            reader = dctx.stream_reader(f, read_size=8192)
            total = 0
            while True:
                try:
                    chunk = reader.read(8192)
                    if not chunk:
                        break
                    out.write(chunk)
                    total += len(chunk)
                except:
                    break
            print(f"Partial recovery: {total} bytes")
            return total > 0
    except Exception as e:
        print(f"Partial recovery failed: {e}")
    
    return False

if __name__ == "__main__":
    aggressive_recover(sys.argv[1])
