import trio
from py_ipfs_lite.peer import Peer
from py_ipfs_lite.config import Config

async def main():
    config = Config(offline=False)
    peer = Peer(config)
    print("Starting peer...")
    await peer.start()

    print("Waiting for bootstrap...")
    await trio.sleep(15)
    
    peers = peer.host.get_network().connections.keys()
    print(f"Connected to {len(peers)} peers.")

    # A well-known small text file ("hello world")
    cid = "QmT78zSuBmuS4z925WZfrqQ1qHaJ56DQaTfyMUF7F8ff5o"
    print(f"Fetching CID: {cid}")
    
    try:
        data = await peer.get_file(cid, timeout=40)
        print(f"Success! Fetched {len(data) if isinstance(data, bytes) else 'stream'} bytes.")
        if isinstance(data, bytes):
            print(f"Data: {data.decode('utf-8', errors='replace')}")
    except Exception as e:
        print(f"Error fetching file: {e}")

    await peer.stop()

if __name__ == "__main__":
    trio.run(main)
