"""Small primitives shared by Super Agent portal routes."""
import bcrypt
import hashlib
import re
import secrets

_PASSWORD_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789-_"


def normalize_phone(value: str | None) -> str:
    digits = re.sub(r"[^0-9]", "", value or "")
    if digits.startswith("0062"):
        digits = digits[2:]
    if digits.startswith("62"):
        national = digits[2:]
    elif digits.startswith("0"):
        national = digits[1:]
    else:
        national = digits
    if not national.startswith("8") or not 9 <= len(national) <= 13:
        raise ValueError("Nomor WhatsApp harus nomor seluler Indonesia yang valid.")
    return "+62" + national


def generate_initial_password() -> str:
    # 24 uniformly selected characters from a 60-character alphabet.
    return "".join(secrets.choice(_PASSWORD_ALPHABET) for _ in range(24))


def hash_password(password: str) -> str:
    raw = password.encode("utf-8")
    if not 12 <= len(raw) <= 72:
        raise ValueError("Password harus 12 sampai 72 byte.")
    return bcrypt.hashpw(raw, bcrypt.gensalt(rounds=12)).decode("ascii")


def verify_password(password: str, encoded_hash: str | None) -> bool:
    if not encoded_hash:
        return False
    try:
        return bcrypt.checkpw(password.encode("utf-8"), encoded_hash.encode("ascii"))
    except (ValueError, TypeError, UnicodeError):
        return False


def hash_token(token: str) -> str:
    return hashlib.sha256(token.encode("ascii")).hexdigest()
