"""
JWT token management - Feature 4

Handles JWT access token creation and validation using Rust crypto.
"""

from typing import Dict, Any
from datetime import timedelta

from .config import AuthConfig
from .models import User

# Import Rust JWT functions
try:
    from .irene_auth import jwt_encode, jwt_decode
except ImportError:
    import irene_auth as _rust
    jwt_encode = _rust.jwt_encode
    jwt_decode = _rust.jwt_decode


class JWTManager:
    """
    JWT access token manager - Feature 4
    
    Handles creation and validation of JWT access tokens for API authentication.
    """
    
    def __init__(self, config: AuthConfig):
        self.config = config
    
    def create_access_token(self, user: User, extra_claims: Dict[str, Any] = None) -> str:
        """
        Create JWT access token for user
        
        Args:
            user: User object
            extra_claims: Additional claims to include
        
        Returns:
            Encoded JWT string
        
        Example:
            >>> token = jwt_manager.create_access_token(user)
            >>> # Use in Authorization: Bearer {token}
        """
        payload = {
            "sub": str(user.id),
            "email": user.email,
            "is_verified": user.is_verified,
            "roles": [role.name for role in user.roles],
        }
        
        if extra_claims:
            payload.update(extra_claims)
        
        exp_seconds = self.config.access_token_expire_minutes * 60
        key = self.config.get_private_key()
        
        return jwt_encode(
            payload,
            key,
            exp_seconds,
            self.config.algorithm
        )
    
    def decode_access_token(self, token: str) -> Dict[str, Any]:
        """
        Decode and validate JWT access token
        
        Args:
            token: JWT string
        
        Returns:
            Decoded claims dictionary
        
        Raises:
            ValueError: If token is invalid or expired
        """
        key = self.config.get_public_key()
        return jwt_decode(token, key, [self.config.algorithm])
