"""Encrypts a subscription link for Sligate: sligate://crypt1/...

    pip install cryptography
    python encrypt.py https://sub.example.com/abc

Or import sligate_link() into a bot. Only Sligate can open the result; the
format is described in src-tauri/core/src/crypt.rs.
"""

import base64
import os
import sys

from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.hkdf import HKDF

SLIGATE_PUBLIC_KEY = "H6dVq8oXUV_fSqVUWPDYQ90djhURBoYe4z4daEQ39Xk"


def _b64decode(text: str) -> bytes:
    return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))


def sligate_link(subscription_url: str, public_key: str = SLIGATE_PUBLIC_KEY) -> str:
    recipient = _b64decode(public_key)
    ephemeral = X25519PrivateKey.generate()
    ephemeral_public = ephemeral.public_key().public_bytes(
        serialization.Encoding.Raw, serialization.PublicFormat.Raw
    )
    shared = ephemeral.exchange(X25519PublicKey.from_public_bytes(recipient))
    key = HKDF(
        algorithm=hashes.SHA256(), length=32, salt=ephemeral_public + recipient, info=b"sligate crypt1"
    ).derive(shared)
    nonce = os.urandom(12)
    sealed = AESGCM(key).encrypt(nonce, subscription_url.strip().encode(), None)
    data = base64.urlsafe_b64encode(ephemeral_public + nonce + sealed).rstrip(b"=").decode()
    return "sligate://crypt1/" + data


if __name__ == "__main__":
    if len(sys.argv) != 2:
        sys.exit("usage: python encrypt.py <subscription-url>")
    print(sligate_link(sys.argv[1]))
