"""
Verify JWT token function - standalone.
"""

from typing import Dict, Any

from apexsaas.core.security.jwt import decode_token as _verify_jwt_token
from apexsaas.exceptions import ApexValidationError, ApexAuthError


async def verify_token(
    token: str,
    jwt_secret: str,
    algorithm: str | None = None,
) -> Dict[str, Any]:
    """
    Verify JWT token (async).
    
    Args:
        token: JWT access token
        jwt_secret: Secret key for JWT
        algorithm: JWT algorithm (default: HS256)
    
    Returns:
        dict with token payload:
        {
            'payload': dict,
            'valid': bool
        }
    
    Raises:
        ApexValidationError: If input validation fails
        ApexAuthError: If token is invalid or expired
    """
    if not token:
        raise ApexValidationError("Token is required")
    if not jwt_secret:
        raise ApexValidationError("jwt_secret is required")
    
    try:
        algorithms = [algorithm] if algorithm else ["HS256"]
        payload = _verify_jwt_token(token, secret_key=jwt_secret, algorithms=algorithms)
        return {
            'payload': payload,
            'valid': True,
            'expires_at': payload.get('exp')
        }
    except Exception as e:
        raise ApexAuthError(f"Invalid or expired token: {str(e)}")


def verify_token_sync(
    token: str,
    jwt_secret: str,
    algorithm: str | None = None,
) -> Dict[str, Any]:
    """Sync wrapper for verify_token."""
    from apexsaas.core.utils.async_runner import run_async
    try:
        return run_async(verify_token(
            token=token,
            jwt_secret=jwt_secret,
            algorithm=algorithm
        ))
    except Exception as e:
        raise ApexAuthError(f"Token verification failed: {str(e)}")
