"""
密码哈希工具模块
支持bcrypt加密和SHA256兼容性验证
"""
import bcrypt
import hashlib
from app_logger import get_logger
logger = get_logger(__name__)


def hash_password_bcrypt(password):
    """
    使用bcrypt加密密码

    Args:
        password: 明文密码

    Returns:
        str: bcrypt哈希值(包含盐值)
    """
    salt = bcrypt.gensalt(rounds=12)
    return bcrypt.hashpw(password.encode('utf-8'), salt).decode('utf-8')


def verify_password_bcrypt(password, password_hash):
    """
    验证bcrypt密码

    Args:
        password: 明文密码
        password_hash: bcrypt哈希值

    Returns:
        bool: 验证成功返回True
    """
    try:
        return bcrypt.checkpw(password.encode('utf-8'),
                             password_hash.encode('utf-8'))
    except Exception as e:
        logger.error(f"bcrypt验证异常: {e}")
        return False


def is_sha256_hash(password_hash):
    """
    判断是否为旧的SHA256哈希

    Args:
        password_hash: 哈希值

    Returns:
        bool: SHA256哈希为64位十六进制字符串
    """
    if not password_hash:
        return False
    # SHA256输出固定64位十六进制
    return len(password_hash) == 64 and all(c in '0123456789abcdef' for c in password_hash.lower())


def verify_password_sha256(password, password_hash):
    """
    验证旧的SHA256密码(兼容性)

    Args:
        password: 明文密码
        password_hash: SHA256哈希值

    Returns:
        bool: 验证成功返回True
    """
    try:
        computed_hash = hashlib.sha256(password.encode()).hexdigest()
        return computed_hash == password_hash
    except Exception as e:
        logger.error(f"SHA256验证异常: {e}")
        return False
