"""
Example 2: Autonomous Agent with Budget Control

Demonstrates:
- Agent with spending budget
- Automatic payment decisions
- Budget tracking
- Error handling
"""
from route402 import Route402Client, PaymentStatus
from route402.exceptions import APIError, ValidationError, PaymentError
from typing import Optional


class AutonomousAgent:
    """
    AI agent with autonomous payment capabilities and budget control
    """

    def __init__(self, api_key: str, daily_budget: float = 10.0):
        """
        Initialize agent

        Args:
            api_key: Route402 API key
            daily_budget: Maximum daily spending in USDC
        """
        self.client = Route402Client(api_key=api_key)
        self.daily_budget = daily_budget
        self.spent_today = 0.0

    def can_afford(self, amount: float) -> bool:
        """Check if agent can afford this payment"""
        return (self.spent_today + amount) <= self.daily_budget

    def buy_service(self, seller: str, amount: str, service_name: str) -> Optional[str]:
        """
        Buy a service if within budget

        Args:
            seller: Service provider address
            amount: Price in USDC
            service_name: Name of service

        Returns:
            Payment ID if successful, None if failed
        """
        amount_float = float(amount)

        # Budget check
        if not self.can_afford(amount_float):
            remaining = self.daily_budget - self.spent_today
            print(f"❌ Cannot afford {service_name} (${amount})")
            print(f"   Daily budget: ${self.daily_budget}")
            print(f"   Spent today: ${self.spent_today}")
            print(f"   Remaining: ${remaining}")
            return None

        # Attempt payment
        try:
            print(f"\n💰 Purchasing {service_name} for ${amount}...")
            payment = self.client.create_payment(
                seller=seller,
                amount=amount,
                reference=f"agent-purchase-{service_name}"
            )

            # Update budget
            self.spent_today += amount_float

            print(f"✅ Purchased {service_name}!")
            print(f"   Payment ID: {payment.id}")
            print(f"   Net cost: ${payment.fee_amount + amount_float} (incl. 0.5% fee)")
            print(f"   Remaining budget: ${self.daily_budget - self.spent_today}")

            return payment.id

        except ValidationError as e:
            print(f"❌ Invalid payment details: {e}")
            return None
        except APIError as e:
            print(f"❌ API error: {e.message}")
            return None
        except PaymentError as e:
            print(f"❌ Payment failed: {e}")
            return None

    def get_spending_summary(self) -> dict:
        """Get spending summary"""
        return {
            "daily_budget": self.daily_budget,
            "spent": self.spent_today,
            "remaining": self.daily_budget - self.spent_today,
            "utilization_pct": (self.spent_today / self.daily_budget) * 100
        }


# Example: Trading agent buying signals
if __name__ == "__main__":
    # Initialize agent with $5 daily budget
    agent = AutonomousAgent(api_key="apk_your_key_here", daily_budget=5.0)

    # Agent decides to buy premium signals
    services = [
        {
            "name": "Premium BTC Signal",
            "seller": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
            "price": "0.05",
            "condition": lambda: True  # Always buy (in real scenario, check market conditions)
        },
        {
            "name": "ETH Price Prediction",
            "seller": "0x55ee389d29bC190cE74F458bAEbe0A88fdABbf83",
            "price": "0.10",
            "condition": lambda: True
        },
        {
            "name": "Market Analysis Report",
            "seller": "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb",
            "price": "0.50",
            "condition": lambda: True
        },
        {
            "name": "Whale Alerts Feed",
            "seller": "0x55ee389d29bC190cE74F458bAEbe0A88fdABbf83",
            "price": "2.00",
            "condition": lambda: True
        }
    ]

    # Agent autonomously decides what to buy
    print("🤖 Autonomous Agent Starting...")
    print(f"💰 Daily Budget: ${agent.daily_budget}\n")

    for service in services:
        if service["condition"]():
            agent.buy_service(
                seller=service["seller"],
                amount=service["price"],
                service_name=service["name"]
            )

    # Summary
    print("\n" + "="*50)
    print("📊 Spending Summary")
    print("="*50)
    summary = agent.get_spending_summary()
    print(f"Budget: ${summary['daily_budget']}")
    print(f"Spent: ${summary['spent']}")
    print(f"Remaining: ${summary['remaining']}")
    print(f"Utilization: {summary['utilization_pct']:.1f}%")
