# For setup instructions, see: https://docs.snath.ai/guides/litellm_setup/

import requests
from lar import GraphState, GraphExecutor, ToolNode, AddValueNode, apply_diff, summarize_diff

# --- Generated by Lár Integration Builder ---
# Request: "I need a tool that checks the current price of a cryptocurrency using CoinCap API."

def get_crypto_price(state):
    """
    Fetches crypto price from CoinCap.
    Expects state key: 'coin_id' (e.g., 'bitcoin')
    """
    coin_id = state.get("coin_id", "bitcoin")
    url = f"https://api.coincap.io/v2/assets/{coin_id}"
    
    try:
        response = requests.get(url, timeout=5)
        response.raise_for_status()
        data = response.json()
        
        # Extract relevant data
        price_usd = data["data"]["priceUsd"]
        symbol = data["data"]["symbol"]
        
        return {
            "crypto_price": float(price_usd),
            "crypto_symbol": symbol,
            "crypto_status": "success"
        }
    except Exception as e:
        return {
            "crypto_error": str(e),
            "crypto_status": "error"
        }

# Define the Node
crypto_tool = ToolNode(
    tool_function=get_crypto_price,
    input_keys=["__state__"],
    output_key=None, # Merges result (price, symbol) into State
    next_node=None   # Wiring handled below
)

# --- End Generated Code ---

# Wiring it up for a test run
if __name__ == "__main__":
    print("--- Testing Integration Builder Pattern: Crypto Tool ---")
    
    # Simple finish node
    final_step = AddValueNode(key="final_msg", value="Done", next_node=None)
    
    # Link tool to finish
    crypto_tool.next_node = final_step
    
    # Run it
    executor = GraphExecutor()
    initial_state = {"coin_id": "ethereum"}
    
    print(f"Input State: {initial_state}")
    
    for step in executor.run_step_by_step(crypto_tool, initial_state):
        print(f"\n[Step] {step['node']}")
        # print(summarize_diff(step.diff)) # verify log formatter too if available, but keep simple
        for k, v in step["state_diff"].items():
            print(f"  -> {k}: {v}")
            
    print("\nTest Complete.")
