"""Encryption of the saved WhatsApp token, one-way hashing of codes and client keys, and phone-number helpers."""

from __future__ import annotations

import base64
import hashlib
import hmac
import re
import secrets

from cryptography.exceptions import InvalidTag
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

_PHONE_NOISE = re.compile(r"[\s\-().]")
_E164 = re.compile(r"^\+[1-9]\d{7,14}$")


class Vault:
    """AES-256-GCM for the WhatsApp token and an HMAC key for the codes, both derived from AUTH_MASTER_KEY."""

    def __init__(self, master_key: str) -> None:
        raw = master_key.encode()
        self._enc_key = hashlib.sha256(b"abos-auth/enc/" + raw).digest()
        self._mac_key = hashlib.sha256(b"abos-auth/mac/" + raw).digest()

    def encrypt(self, plain: str) -> str:
        nonce = secrets.token_bytes(12)
        return base64.b64encode(nonce + AESGCM(self._enc_key).encrypt(nonce, plain.encode(), None)).decode()

    def decrypt(self, stored: str) -> str | None:
        """None when the value cannot be read (for example the master key changed)."""
        try:
            blob = base64.b64decode(stored)
            return AESGCM(self._enc_key).decrypt(blob[:12], blob[12:], None).decode()
        except (InvalidTag, ValueError):
            return None

    def code_hash(self, request_id: str, code: str) -> str:
        return hmac.new(self._mac_key, f"{request_id}:{code}".encode(), hashlib.sha256).hexdigest()


def new_client_key() -> tuple[str, str, str]:
    """(key_id, secret, full_key). Only sha256(secret) is stored; the full key is shown once."""
    key_id = secrets.token_hex(4)
    secret = secrets.token_urlsafe(32)
    return key_id, secret, f"wak_{key_id}.{secret}"


def split_client_key(presented: str) -> tuple[str, str] | None:
    if not presented.startswith("wak_") or "." not in presented:
        return None
    key_id, _, secret = presented[4:].partition(".")
    return (key_id, secret) if key_id and secret else None


def hash_secret(secret: str) -> str:
    return hashlib.sha256(secret.encode()).hexdigest()


def same(a: str, b: str) -> bool:
    return hmac.compare_digest(a.encode(), b.encode())


def normalize_phone(raw: str) -> str:
    """E.164 with a leading +. Spaces, dashes, dots and brackets are dropped and a leading 00 becomes +."""
    cleaned = _PHONE_NOISE.sub("", raw or "")
    if cleaned.startswith("00"):
        cleaned = "+" + cleaned[2:]
    if not _E164.match(cleaned):
        raise ValueError("phone must be an international number such as +12027717005")
    return cleaned


def mask_phone(phone: str) -> str:
    return phone[:2] + "*" * max(len(phone) - 6, 0) + phone[-4:]
