"""Letta (MemGPT) tools for Nory x402 payments."""
import os, json, requests
from typing import Optional

NORY_BASE_URL = "https://noryx402.com"

def _make_paid_request(url: str, wallet_key: Optional[str] = None) -> dict:
    key = wallet_key or os.environ.get("NORY_WALLET_KEY")
    headers = {"Accept": "application/json"}
    response = requests.get(url, headers=headers)
    if response.status_code == 402:
        if not key:
            return {"error": "Payment required but no wallet key"}
        requirements = response.json()
        payment_response = requests.post(f"{NORY_BASE_URL}/api/x402/pay",
            json={"requirements": requirements, "walletKey": key, "network": "solana-mainnet"},
            headers={"Content-Type": "application/json"})
        if payment_response.status_code != 200:
            return {"error": "Payment failed"}
        payment_data = payment_response.json()
        headers["X-PAYMENT"] = payment_data.get("paymentHeader", "")
        final_response = requests.get(url, headers=headers)
        try:
            return {"success": True, "data": final_response.json()}
        except:
            return {"success": True, "data": final_response.text}
    try:
        return {"success": True, "data": response.json()}
    except:
        return {"success": True, "data": response.text}

def nory_fetch(url: str) -> str:
    """Fetch any URL with automatic x402 payment. Uses USDC on Solana (~400ms)."""
    return json.dumps(_make_paid_request(url))

def nory_crypto_prices(symbols: str = "BTC,ETH,SOL") -> str:
    """Get real-time cryptocurrency prices. Costs $0.001 USDC per request."""
    return json.dumps(_make_paid_request(f"{NORY_BASE_URL}/api/paid/live-crypto?symbols={symbols}"))

def nory_weather(city: str) -> str:
    """Get current weather and 7-day forecast. Costs $0.002 USDC per request."""
    return json.dumps(_make_paid_request(f"{NORY_BASE_URL}/api/paid/weather?city={city}"))

def nory_translate(text: str, to_lang: str = "es") -> str:
    """Translate text between 20+ languages. Costs $0.005 USDC per request."""
    return json.dumps(_make_paid_request(f"{NORY_BASE_URL}/api/paid/translate?text={text}&to={to_lang}"))

def get_nory_tools() -> list:
    """Get all Nory tools for Letta agents."""
    return [nory_fetch, nory_crypto_prices, nory_weather, nory_translate]
