"""One password policy for NEW passwords of CRM accounts, and the generator of initial passwords.

Applies when a password is SET (master `change_password`, own `update_profile`, initial password of a new agent) - never at login, so
existing accounts keep working until their password is changed. Only the standard library; no environment, SQL or Flask.

Policy
  * at least PASSWORD_MIN_LENGTH (12) characters;
  * not equal to the login or to obvious identity data of the account (first name, last name, `first.last`, `last.first`, `firstlast`,
    the e-mail address and its local part, phone number digits, licence number). Comparison ignores case, spaces and `. _ - @ + ( )`, so
    `Jan.Kowalski`, `jan kowalski` and `JANKOWALSKI` are all "the login".
Initial passwords: PASSWORD_GENERATED_LENGTH (16) characters from `secrets`, alphabet without easily confused characters
(no 0 O 1 l I), at least one upper-case letter, one lower-case letter and one digit.
"""
import re
import secrets

PASSWORD_MIN_LENGTH = 12
PASSWORD_GENERATED_LENGTH = 16

_UPPER = 'ABCDEFGHJKLMNPQRSTUVWXYZ'          # no I, O
_LOWER = 'abcdefghjkmnpqrstuvwxyz'           # no i, l, o
_DIGITS = '23456789'                          # no 0, 1
ALPHABET = _UPPER + _LOWER + _DIGITS

MESSAGE_TOO_SHORT = f'Hasło musi mieć co najmniej {PASSWORD_MIN_LENGTH} znaków.'
MESSAGE_PREDICTABLE = 'Hasło nie może być takie samo jak login ani zawierać wyłącznie danych identyfikacyjnych konta (imię, nazwisko, e-mail, telefon).'


def generate_initial_password():
    """16 random characters, never derived from any account data."""
    while True:
        candidate = ''.join(secrets.choice(ALPHABET) for _ in range(PASSWORD_GENERATED_LENGTH))
        if (any(c in _UPPER for c in candidate) and any(c in _LOWER for c in candidate) and any(c in _DIGITS for c in candidate)):
            return candidate


def _squash(value):
    return re.sub(r'[\s._@\-+()]+', '', str(value or '').casefold())


def _identity_forms(login, first_name, last_name, email, phone, licence):
    first, last = _squash(first_name), _squash(last_name)
    forms = {_squash(login), first, last, first + last, last + first}
    address = str(email or '').strip()
    if address:
        forms |= {_squash(address), _squash(address.split('@', 1)[0])}
    digits = re.sub(r'\D+', '', str(phone or ''))
    if digits:
        forms.add(digits)
    forms.add(_squash(licence))
    return {form for form in forms if form}


def validate_new_password(password, *, login='', first_name='', last_name='', email='', phone='', licence=''):
    """None when the password is acceptable, otherwise a user-facing Polish message."""
    if not isinstance(password, str) or len(password) < PASSWORD_MIN_LENGTH:
        return MESSAGE_TOO_SHORT
    if _squash(password) in _identity_forms(login, first_name, last_name, email, phone, licence):
        return MESSAGE_PREDICTABLE
    return None
