"""Contains a mix of dev utilities like running FastAPI in a notebook or creating test wallets."""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/03_utils.ipynb.

# %% auto 0
__all__ = ['create_test_wallet', 'is_port_free', 'wait_port_free', 'ServerManager']

# %% ../nbs/03_utils.ipynb 3
def create_test_wallet(fund=True):
    import os
    from cdp import Cdp, Wallet
    Cdp.configure(api_key_name=os.getenv("CDP_KEY_NAME"), private_key=os.getenv("CDP_PRIVATE_KEY"))

    wallet = Wallet.create('base-sepolia')
    if fund:    
        faucet_tx = wallet.faucet('usdc')
        faucet_tx.wait()
        faucet_tx = wallet.faucet('eth')
        faucet_tx.wait()
    return wallet

# %% ../nbs/03_utils.ipynb 5
import asyncio, socket, time
from threading import Thread
import uvicorn

# %% ../nbs/03_utils.ipynb 6
def is_port_free(port, host='localhost'):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        sock.bind((host, port))
        return True
    except OSError: return False
    finally: sock.close()

def wait_port_free(port, host='localhost', max_wait=3):
    start = time.time()
    while not is_port_free(port):
        if time.time() - start > max_wait: return False
        time.sleep(0.1)
    return True

class ServerManager:
    def __init__(self, app, port=8000, host='0.0.0.0'):
        self.server = uvicorn.Server(uvicorn.Config(app, host=host, port=port))
        
    def start(self):
        Thread(target=lambda: asyncio.run(self.server.serve()), daemon=True).start()
        while not self.server.started: time.sleep(0.01)
        return self
        
    def stop(self):
        if self.server.started:
            self.server.should_exit = True
            wait_port_free(self.server.config.port)
        return True
