"""
Basic usage example for Authevo Python SDK.

Demonstrates:
- Configuration via environment variables
- Generating a new agent
- Executing an action with retry logic
- Error handling
"""

import asyncio
from authevo import AuthevoAgent, AuthevoConfig, PolicyDeniedError, NetworkError


async def main():
    # Load config from environment (or use defaults for local dev)
    config = AuthevoConfig.from_env()
    
    print("Authevo SDK Demo")
    print(f"API URL: {config.api_url}")
    print(f"Environment: {'Production' if config.is_production else 'Local'}")
    print()
    
    # Generate a new agent
    async with AuthevoAgent.generate(config=config) as agent:
        print(f"Agent DID: {agent.keypair.did}")
        print()
        
        # Register the agent
        try:
            print("Registering agent...")
            registration = await agent.register(name="Demo Agent")
            print(f"✓ Agent registered: {registration.get('id', 'N/A')}")
            print()
        except Exception as e:
            print(f"✗ Registration failed: {e}")
            return
        
        # Example 1: Permitted action
        print("Example 1: Permitted action (amount <= $100)")
        try:
            result = await agent.execute_action(
                action="refund",
                payload={"orderId": "order-123", "amount": 50}
            )
            print(f"✓ Action submitted successfully")
            print(f"  Action ID: {result.get('id', 'N/A')}")
            print(f"  Decision: {result.get('policyDecision', {}).get('decision', 'N/A')}")
            print()
        except PolicyDeniedError as e:
            print(f"✗ Action denied: {e.reason}")
            print()
        except NetworkError as e:
            print(f"✗ Network error: {e}")
            print()
        
        # Example 2: Denied action
        print("Example 2: Denied action (amount > $100)")
        try:
            result = await agent.execute_action(
                action="refund",
                payload={"orderId": "order-456", "amount": 150}
            )
            print(f"✓ Action submitted (but may be denied by policy)")
            print(f"  Decision: {result.get('policyDecision', {}).get('decision', 'N/A')}")
            print()
        except PolicyDeniedError as e:
            print(f"✓ Expected: Action denied by policy")
            print(f"  Reason: {e.reason}")
            print(f"  Policy: {e.policy_id}")
            print()
        
        print("Demo complete!")


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