import bcrypt

# Pre-computed bcrypt hash for timing-safe comparisons when user is not found.
_DUMMY_HASH = "$2b$12$LJ3m4ys3Lg2VBe4sFNGDe.NU0TGi5LjGnS/RhOsKNBQPNKZHPIsfG"


def hash_password(plain: str) -> str:
    return bcrypt.hashpw(plain.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")


def verify_password(plain: str, hashed: str) -> bool:
    return bcrypt.checkpw(plain.encode("utf-8"), hashed.encode("utf-8"))


def verify_password_timing_safe(plain: str, hashed: str | None) -> bool:
    """
    Verify a password, falling back to a dummy hash if hashed is None.
    Prevents timing-based user enumeration.
    """
    target = hashed if hashed is not None else _DUMMY_HASH
    return verify_password(plain, target) and hashed is not None
