"""
Network integration test: fetch a well-known file from the IPFS network.

Connects to the IPFS DHT via bootstrap peers, finds providers for a
well-known CID, and retrieves the file via Bitswap.

Usage:
    uv run python test_network_fetch.py
"""

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

# Well-known CID: "hello world" text file, widely pinned on the IPFS network
WELL_KNOWN_CID = "QmT78zSuBmuS4z925WZfrqQ1qHaJ56DQaTfyMUF7F8ff5o"
WELL_KNOWN_CONTENT = b"hello world\n"


async def main():
    config = Config(
        offline=False,
        reprovide_interval_seconds=-1,  # don't reprovide during test
        default_timeout=60.0,
    )

    peer = Peer(config, listen_addrs=["/ip4/0.0.0.0/tcp/0"])
    await peer.start()

    try:
        # 1. Bootstrap to the IPFS network
        from py_ipfs_lite.cli import DEFAULT_BOOTSTRAP_PEERS

        print(f"Bootstrapping to {len(DEFAULT_BOOTSTRAP_PEERS)} peers...")
        await peer.bootstrap(DEFAULT_BOOTSTRAP_PEERS)

        # Wait a bit for DHT discovery
        await trio.sleep(5)

        conns = peer.host.get_network().connections
        print(f"Connected to {len(conns)} peers")

        if len(conns) == 0:
            print("ERROR: No peers connected — cannot fetch from network")
            return

        # 2. Fetch the file
        print(f"Fetching CID: {WELL_KNOWN_CID}")

        result = await peer.get_file(WELL_KNOWN_CID, timeout=60)

        # result is now a SeekableReader; read all bytes
        data = await result.read()

        print(f"Fetched {len(data)} bytes")
        print(f"Content: {data!r}")

        assert data == WELL_KNOWN_CONTENT, (
            f"Content mismatch! Expected {WELL_KNOWN_CONTENT!r}, got {data!r}"
        )
        print("SUCCESS: Content matches expected value")

        # 3. Test seeking
        result.seek(0)
        partial = await result.read(5)
        assert partial == b"hello", f"Seek+read failed: got {partial!r}"
        print("SUCCESS: SeekableReader seek works")

    except Exception as e:
        print(f"FAILED: {e}")
        import traceback
        traceback.print_exc()
    finally:
        await peer.close()


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