"""
JWT Authentication - Token generation and validation.
"""

import os
import jwt
from datetime import datetime, timedelta
from typing import Optional, Dict
import structlog

logger = structlog.get_logger(__name__)


class JWTAuth:
    """JWT token management."""
    
    def __init__(self):
        self.secret_key = os.getenv('JWT_SECRET_KEY', 'dev-secret-change-in-production')
        self.algorithm = os.getenv('JWT_ALGORITHM', 'HS256')
        self.expiry_hours = int(os.getenv('JWT_EXPIRY_HOURS', '24'))
    
    def create_token(self, license_key: str, email: str, tier: str) -> str:
        """
        Create JWT token.
        
        Args:
            license_key: User's license key
            email: User's email
            tier: Subscription tier
            
        Returns:
            JWT token string
        """
        payload = {
            'license_key': license_key,
            'email': email,
            'tier': tier,
            'exp': datetime.utcnow() + timedelta(hours=self.expiry_hours),
            'iat': datetime.utcnow()
        }
        
        token = jwt.encode(payload, self.secret_key, algorithm=self.algorithm)
        
        logger.info("jwt_token_created", email=email, tier=tier)
        
        return token

    def create_refresh_token(self, license_key: str, email: str) -> str:
        """
        Create long-lived refresh token.
        """
        payload = {
            'sub': license_key,
            'email': email,
            'type': 'refresh',
            'exp': datetime.utcnow() + timedelta(days=7),
            'iat': datetime.utcnow()
        }
        
        token = jwt.encode(payload, self.secret_key, algorithm=self.algorithm)
        return token
    
    def verify_token(self, token: str) -> Optional[Dict]:
        """
        Verify and decode JWT token.
        
        Args:
            token: JWT token string
            
        Returns:
            Decoded payload if valid, None otherwise
        """
        try:
            payload = jwt.decode(
                token,
                self.secret_key,
                algorithms=[self.algorithm]
            )
            return payload
        
        except jwt.ExpiredSignatureError:
            logger.warning("jwt_token_expired")
            return None
        
        except jwt.InvalidTokenError as e:
            logger.warning("jwt_token_invalid", error=str(e))
            return None


# Global JWT auth instance
jwt_auth = JWTAuth()
