"""
Cuchulufm is a series of wrappers for bottlepy, mako and others and construct a simple headless cms.

Copyright (C) 2024 Antonio de la Rosa Caballero

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
"""

from hashlib import sha512, sha256
from base64 import b64encode
from os import urandom
import string
import secrets

# Functions for create random strings usando urandom

def create_key_encrypt(n=10):
    """ Simple function for create a random string
    
    Simple function for create a random string based in sha512
    
    Args:
        n (int): size of string random bytes (view urandom function in Python3 Help)
    """
    
    return sha512(urandom(n)).hexdigest()

def create_key_encrypt_256(n=10):
    
    """ Simple function for create a random string
    
    Simple function for create a random string based in sha256
    
    Args:
        n (int): size of string random bytes (view urandom function in Python3 Help)
    """
    
    return sha256(urandom(n)).hexdigest()

def create_key(n=10):
    
    """ Simple function for create a random string
    
    Simple function for create a random string based in urandom function and base64 encoding
    
    Args:
        n (int): size of string random bytes (view urandom function in Python3 Help)
    """
    
    rand_bytes=urandom(n)
    
    return b64encode(rand_bytes).decode('utf-8')[0:-2]

def create_simple_password(n=14):
    
    """ Based in python3 documentation for create passwords using secrets module
    
    https://docs.python.org/3/library/secrets.html
    
    Args:
        n (int): Number of random elements of the password
    
    """
    
    password=''
    
    alphabet=string.ascii_letters+string.digits+string.punctuation
    
    while True:
        password=''.join(secrets.choice(alphabet) for i in range(n))
        if (any(c.islower() for c in password) and any(c.isupper() for c in password) and sum(c.isdigit() for c in password) >= 3):
            break
    
    return password

