# Copyright (c) 2023-present Plane Software, Inc. and contributors
# SPDX-License-Identifier: AGPL-3.0-only
# See the LICENSE file for details.

import re

from zxcvbn import zxcvbn

PASSWORD_MIN_LENGTH = 8
PASSWORD_UPPERCASE_REGEX = re.compile(r"[A-Z]")
PASSWORD_LOWERCASE_REGEX = re.compile(r"[a-z]")
PASSWORD_DIGIT_REGEX = re.compile(r"[0-9]")
PASSWORD_SPECIAL_CHAR_REGEX = re.compile(r"""[!@#$%^&*()\-_+=\[\]{}|;:'",.<>?/]""")


def has_required_password_complexity(password: str) -> bool:
    if len(password) < PASSWORD_MIN_LENGTH:
        return False

    return all(
        (
            PASSWORD_UPPERCASE_REGEX.search(password),
            PASSWORD_LOWERCASE_REGEX.search(password),
            PASSWORD_DIGIT_REGEX.search(password),
            PASSWORD_SPECIAL_CHAR_REGEX.search(password),
        )
    )


def is_password_policy_valid(password: str) -> bool:
    if not has_required_password_complexity(password):
        return False

    results = zxcvbn(password)
    return results["score"] >= 3
