"""
Security utilities for OCPP UDP client
"""
import hashlib
import secrets
import logging
from typing import Optional

logger = logging.getLogger(__name__)


def generate_token(length: int = 32) -> str:
    """Generate a secure random token"""
    return secrets.token_urlsafe(length)


def hash_password(password: str, salt: Optional[str] = None) -> tuple[str, str]:
    """Hash a password with salt"""
    if salt is None:
        salt = secrets.token_hex(16)
    
    password_hash = hashlib.pbkdf2_hmac(
        'sha256',
        password.encode('utf-8'),
        salt.encode('utf-8'),
        100000  # iterations
    )
    
    return password_hash.hex(), salt


def verify_password(password: str, hashed_password: str, salt: str) -> bool:
    """Verify a password against its hash"""
    password_hash, _ = hash_password(password, salt)
    return secrets.compare_digest(password_hash, hashed_password)


def validate_charge_point_id(charge_point_id: str) -> bool:
    """Validate charge point ID format"""
    if not charge_point_id:
        return False
        
    # Basic validation - alphanumeric and hyphens, max 20 chars
    if len(charge_point_id) > 20:
        return False
        
    return charge_point_id.replace('-', '').replace('_', '').isalnum()


class SecurityManager:
    """Manages security for OCPP connections"""
    
    def __init__(self):
        self.active_tokens: set = set()
        
    def create_session_token(self, charge_point_id: str) -> str:
        """Create a session token for a charge point"""
        token = generate_token()
        self.active_tokens.add(token)
        logger.info(f"Created session token for charge point: {charge_point_id}")
        return token
        
    def validate_session_token(self, token: str) -> bool:
        """Validate a session token"""
        return token in self.active_tokens
        
    def revoke_session_token(self, token: str):
        """Revoke a session token"""
        self.active_tokens.discard(token)
        logger.info("Session token revoked")
