"""
CrewAI integration for Authevo.

This module provides a @verifiable_task decorator for CrewAI tasks.
"""

import functools
import asyncio
from typing import Callable, Any

from .agent import AuthevoAgent


def verifiable_task(agent: AuthevoAgent, action: str):
    """
    Decorator that wraps CrewAI tasks with Authevo verification.
    
    This decorator intercepts the task execution, creates a verifiable
    Authevo action, and executes the original task function.
    
    Args:
        agent: AuthevoAgent instance for verification
        action: Action name for Authevo (e.g., "refund", "data_access")
    
    Example:
        >>> agent = AuthevoAgent.generate()
        >>> 
        >>> @verifiable_task(agent=agent, action="refund")
        >>> def process_refund(order_id: str, amount: float):
        ...     # Actual refund logic
        ...     return {"status": "refunded", "amount": amount}
        >>>
        >>> # When called, this will create a verifiable Authevo action
        >>> result = process_refund("order-123", 50.0)
    """
    
    def decorator(func: Callable) -> Callable:
        @functools.wraps(func)
        def sync_wrapper(*args, **kwargs):
            # Build payload from function arguments
            import inspect
            sig = inspect.signature(func)
            bound_args = sig.bind(*args, **kwargs)
            bound_args.apply_defaults()
            payload = dict(bound_args.arguments)
            
            # Execute Authevo action
            try:
                result = asyncio.run(
                    agent.execute_action(
                        action=action,
                        payload=payload
                    )
                )
                
                # If verification succeeded, execute original function
                if result:
                    return func(*args, **kwargs)
                else:
                    raise Exception("Authevo verification failed")
                    
            except Exception as e:
                raise Exception(f"Verifiable task failed: {str(e)}")
        
        @functools.wraps(func)
        async def async_wrapper(*args, **kwargs):
            # Build payload from function arguments
            import inspect
            sig = inspect.signature(func)
            bound_args = sig.bind(*args, **kwargs)
            bound_args.apply_defaults()
            payload = dict(bound_args.arguments)
            
            # Execute Authevo action
            try:
                result = await agent.execute_action(
                    action=action,
                    payload=payload
                )
                
                # If verification succeeded, execute original function
                if result:
                    if asyncio.iscoroutinefunction(func):
                        return await func(*args, **kwargs)
                    else:
                        return func(*args, **kwargs)
                else:
                    raise Exception("Authevo verification failed")
                    
            except Exception as e:
                raise Exception(f"Verifiable task failed: {str(e)}")
        
        # Return appropriate wrapper based on function type
        if asyncio.iscoroutinefunction(func):
            return async_wrapper
        else:
            return sync_wrapper
    
    return decorator
