import re
import secrets
from datetime import datetime
from zoneinfo import ZoneInfo


def generate_license_key(license_type='full'):
    """
    Generate a license key in format: AF-F-YYYYMM-XXXX-YYYY-ZZZZ
    
    AF = Account Factory (Product identifier)
    F/T = F for Full version, T for Test version
    YYYY = Year
    MM = Month
    XXXX-YYYY-ZZZZ = Random alphanumeric characters
    """
    # Allowed characters (without confusing ones like 0/O, 1/I/l)
    chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
    
    # Date part
    now = datetime.now(ZoneInfo("Europe/Berlin"))
    date_part = now.strftime('%Y%m')
    type_char = 'F' if license_type == 'full' else 'T'
    
    # Generate random parts (3 blocks of 4 characters)
    parts = []
    for _ in range(3):
        part = ''.join(secrets.choice(chars) for _ in range(4))
        parts.append(part)
    
    # Assemble key
    key = f"AF-{type_char}-{date_part}-{parts[0]}-{parts[1]}-{parts[2]}"
    
    return key


def validate_license_key(key):
    """
    Validate the License Key Format
    Expected: AF-F-YYYYMM-XXXX-YYYY-ZZZZ or AF-T-YYYYMM-XXXX-YYYY-ZZZZ
    """
    if not key:
        return False
    
    # Pattern for the new format
    # AF- (fixed) + F or T + - + 6 digits (YYYYMM) + - + 4 characters + - + 4 characters + - + 4 characters
    pattern = r'^AF-[FT]-\d{6}-[A-Z0-9]{4}-[A-Z0-9]{4}-[A-Z0-9]{4}$'
    
    # Uppercase for comparison
    return bool(re.match(pattern, key.upper()))