"""Vaikora Python SDK - AI Agent Security Platform."""
from vaikora.client import VaikoraClient
from vaikora.sync_client import VaikoraClientSync
from vaikora.models import (
    Agent,
    AgentType,
    AgentStatus,
    Action,
    ActionResult,
    ActionStatus,
    Policy,
    Alert,
    AlertSeverity,
    AlertStatus,
    # Data Validation
    DataValidationRequest,
    DataValidationResult,
    DataValidationBatchResult,
    DataQualityLevel,
    PIIType,
    PIIDetection,
    AnomalyType,
    AnomalyDetection,
    ToxicityCategory,
    ToxicityDetection,
    CleaningAction,
)
from vaikora.exceptions import (
    VaikoraError,
    AuthenticationError,
    RateLimitError,
    PolicyViolationError,
    NetworkError,
    ValidationError,
    NotFoundError,
)
from vaikora.interceptor import (
    VaikoraInterceptor,
    InterceptorConfig,
    InterceptorResult,
    InterceptorAction,
    ApprovalStatus,
    InterceptorException,
    PolicyDeniedException,
    ValidationException,
    ApprovalRequiredException,
    ApprovalDeniedException,
    ApprovalExpiredException,
    create_interceptor,
)
# SDK Guardrails - Identity, Context, Emergency Controls
from vaikora.identity import (
    AgentIdentity,
    AgentCredentials,
    SignedRequest,
)
from vaikora.context import (
    ExecutionContext,
    ExecutionMode,
    ExecutionTrace,
    ContextLevel,
    get_current_context,
    set_current_context,
    context_scope,
    with_context,
)
from vaikora.emergency import (
    EmergencyController,
    FreezeState,
    FreezeReason,
    FreezeScope,
    CircuitBreaker,
    CircuitBreakerConfig,
    CircuitState,
    CircuitBreakerOpenError,
    AgentFrozenError,
    frozen_guard,
)
from vaikora.openai_wrapper import (
    wrap_openai,
    VaikoraOpenAIWrapper,
)

__version__ = "0.2.0"

# Global client instance for convenience functions
_global_client: VaikoraClient = None
_global_agent_id: str = None


def configure(
    api_key: str,
    base_url: str = "https://api.vaikora.com",
    timeout: float = 30.0,
):
    """
    Configure the global Vaikora client.
    
    Args:
        api_key: Your Vaikora API key
        base_url: API base URL (default: https://api.vaikora.com)
        timeout: Request timeout in seconds
    
    Example:
        >>> import vaikora
        >>> vaikora.configure(api_key="vk_xxx")
    """
    global _global_client
    _global_client = VaikoraClient(
        api_key=api_key,
        base_url=base_url,
        timeout=timeout,
    )


def get_client() -> VaikoraClient:
    """Get the global client instance."""
    if _global_client is None:
        raise RuntimeError(
            "Vaikora client not configured. Call vaikora.configure(api_key=...) first."
        )
    return _global_client


async def register(
    name: str,
    agent_type: str = "autonomous",
    capabilities: list = None,
    metadata: dict = None,
) -> Agent:
    """
    Register a new agent with Vaikora.
    
    This is a convenience function that uses the global client.
    Configure the client first with vaikora.configure().
    
    Args:
        name: Unique name for the agent
        agent_type: One of 'autonomous', 'semi_autonomous', 'human_in_loop', 'api_bridge'
        capabilities: List of capabilities (e.g., ['read', 'write', 'delete'])
        metadata: Additional metadata for the agent
        
    Returns:
        Registered Agent object
    
    Example:
        >>> import vaikora
        >>> vaikora.configure(api_key="vk_xxx")
        >>> agent = await vaikora.register(
        ...     name="my-agent",
        ...     agent_type="autonomous",
        ...     capabilities=["read", "write"],
        ... )
        >>> print(agent.id)
    """
    global _global_agent_id
    client = get_client()
    agent = await client.agents.register(
        name=name,
        agent_type=agent_type,
        capabilities=capabilities or [],
        metadata=metadata or {},
    )
    _global_agent_id = str(agent.id)
    return agent


def register_sync(
    name: str,
    agent_type: str = "autonomous",
    capabilities: list = None,
    metadata: dict = None,
) -> Agent:
    """Synchronous version of register()."""
    import asyncio
    return asyncio.get_event_loop().run_until_complete(
        register(name, agent_type, capabilities, metadata)
    )


async def validate_data(
    data: dict,
    check_pii: bool = True,
    check_anomalies: bool = True,
    check_toxicity: bool = True,
    auto_clean: bool = False,
) -> DataValidationResult:
    """
    Validate data for PII, anomalies, and toxicity.
    
    This is a convenience function that uses the global client.
    
    Args:
        data: Data to validate
        check_pii: Enable PII detection
        check_anomalies: Enable anomaly detection
        check_toxicity: Enable toxicity detection
        auto_clean: Automatically clean detected issues
        
    Returns:
        DataValidationResult with validation details
    
    Example:
        >>> import vaikora
        >>> vaikora.configure(api_key="vk_xxx")
        >>> result = await vaikora.validate_data(
        ...     {"email": "user@example.com", "name": "John"},
        ...     check_pii=True,
        ... )
        >>> if result.pii_detected:
        ...     print(f"PII found: {result.pii_detections}")
    """
    client = get_client()
    request = DataValidationRequest(
        data=data,
        check_pii=check_pii,
        check_anomalies=check_anomalies,
        check_toxicity=check_toxicity,
        auto_clean=auto_clean,
    )
    return await client.validation.validate(request)


def validate_data_sync(
    data: dict,
    check_pii: bool = True,
    check_anomalies: bool = True,
    check_toxicity: bool = True,
    auto_clean: bool = False,
) -> DataValidationResult:
    """Synchronous version of validate_data()."""
    import asyncio
    return asyncio.get_event_loop().run_until_complete(
        validate_data(data, check_pii, check_anomalies, check_toxicity, auto_clean)
    )


def interceptor(
    action_type: str,
    resource: str = None,
    require_approval: bool = False,
    validate_inputs: bool = True,
    validate_outputs: bool = False,
    **kwargs,
):
    """
    Decorator to wrap functions with Vaikora security.
    
    This decorator intercepts function calls to:
    - Validate inputs/outputs for PII, anomalies, toxicity
    - Evaluate security policies
    - Queue for human approval if required
    
    Args:
        action_type: Type of action (e.g., 'database.write')
        resource: Resource being accessed (e.g., 'production')
        require_approval: Whether human approval is required
        validate_inputs: Enable input validation
        validate_outputs: Enable output validation
        **kwargs: Additional InterceptorConfig options
        
    Example:
        >>> import vaikora
        >>> vaikora.configure(api_key="vk_xxx")
        >>> 
        >>> @vaikora.interceptor(
        ...     action_type="database.write",
        ...     resource="production",
        ...     require_approval=True,
        ... )
        ... async def write_data(data: dict):
        ...     # Your code here
        ...     return True
    """
    client = get_client()
    config = InterceptorConfig(
        action_type=action_type,
        resource=resource,
        agent_id=_global_agent_id,
        require_approval=require_approval,
        validate_inputs=validate_inputs,
        validate_outputs=validate_outputs,
        **kwargs,
    )
    return create_interceptor(client=client, config=config)


# Global emergency controller
_emergency_controller: EmergencyController = None


def _get_emergency_controller() -> EmergencyController:
    """Get or create the global emergency controller."""
    global _emergency_controller
    if _emergency_controller is None:
        if _global_agent_id is None:
            raise RuntimeError(
                "Agent not registered. Call vaikora.register() first."
            )
        _emergency_controller = EmergencyController(agent_id=_global_agent_id)
    return _emergency_controller


async def freeze_agent(
    reason: str = "manual",
    scope: str = "all_actions",
    duration_seconds: float = None,
    message: str = None,
) -> FreezeState:
    """
    Immediately freeze the agent.
    
    This stops the agent from performing actions until resumed.
    
    Args:
        reason: Why the agent is being frozen (manual, policy_violation, etc.)
        scope: What actions are affected (all_actions, write_actions, etc.)
        duration_seconds: Auto-unfreeze after this time (optional)
        message: Human-readable message
        
    Returns:
        FreezeState with freeze details
        
    Example:
        >>> import vaikora
        >>> await vaikora.freeze_agent(
        ...     reason="anomaly_detected",
        ...     message="Unusual behavior detected",
        ...     duration_seconds=3600,  # 1 hour
        ... )
    """
    controller = _get_emergency_controller()
    return controller.freeze(
        reason=FreezeReason(reason),
        scope=FreezeScope(scope),
        duration_seconds=duration_seconds,
        message=message,
    )


async def resume_agent(
    verified: bool = True,
    notes: str = None,
) -> FreezeState:
    """
    Resume agent operations after a freeze.
    
    Args:
        verified: Whether verification checks passed
        notes: Notes about the resume
        
    Returns:
        Updated FreezeState (should show is_frozen=False)
        
    Example:
        >>> import vaikora
        >>> await vaikora.resume_agent(notes="Issue resolved")
    """
    controller = _get_emergency_controller()
    return controller.resume(
        verification_passed=verified,
        notes=notes,
    )


def is_agent_frozen() -> bool:
    """Check if the agent is currently frozen."""
    try:
        controller = _get_emergency_controller()
        return controller.is_frozen
    except RuntimeError:
        return False


def get_freeze_state() -> FreezeState:
    """Get the current freeze state."""
    controller = _get_emergency_controller()
    return controller.freeze_state


__all__ = [
    # Configuration
    "configure",
    "get_client",
    # Convenience functions
    "register",
    "register_sync",
    "validate_data",
    "validate_data_sync",
    "interceptor",
    "freeze_agent",
    "resume_agent",
    # Clients
    "VaikoraClient",
    "VaikoraClientSync",
    # Interceptor
    "VaikoraInterceptor",
    "InterceptorConfig",
    "InterceptorResult",
    "InterceptorAction",
    "ApprovalStatus",
    "create_interceptor",
    # Identity
    "AgentIdentity",
    "AgentCredentials",
    "SignedRequest",
    # Context
    "ExecutionContext",
    "ExecutionMode",
    "ExecutionTrace",
    "ContextLevel",
    "get_current_context",
    "set_current_context",
    "context_scope",
    "with_context",
    # Emergency Controls
    "EmergencyController",
    "FreezeState",
    "FreezeReason",
    "FreezeScope",
    "CircuitBreaker",
    "CircuitBreakerConfig",
    "CircuitState",
    "CircuitBreakerOpenError",
    "AgentFrozenError",
    "frozen_guard",
    # Models
    "Agent",
    "AgentType",
    "AgentStatus",
    "Action",
    "ActionResult",
    "ActionStatus",
    "Policy",
    "Alert",
    "AlertSeverity",
    "AlertStatus",
    "PIIDetection",
    "AnomalyType",
    "AnomalyDetection",
    "ToxicityCategory",
    "ToxicityDetection",
    "CleaningAction",
    # Exceptions
    "VaikoraError",
    "AuthenticationError",
    "RateLimitError",
    "PolicyViolationError",
    "NetworkError",
    "ValidationError",
    "NotFoundError",
    # OpenAI Wrapper
    "wrap_openai",
    "VaikoraOpenAIWrapper",
    # Interceptor Exceptions
    "InterceptorException",
    "PolicyDeniedException",
    "ValidationException",
    "ApprovalRequiredException",
    "ApprovalDeniedException",
    "ApprovalExpiredException",
]
