"""harbor0 end-to-end encryption, format h0e1, for Python 3.9+.

Everything here runs on your own computer. The server only ever sees the
wrapped keys, encrypted names and encrypted file contents.

    pip install cryptography argon2-cffi
"""
from __future__ import annotations

import base64
import hashlib
import hmac
import math
import os
import re
import struct
import unicodedata
from typing import BinaryIO, Iterator

from argon2.low_level import Type, hash_secret_raw
from cryptography.exceptions import InvalidTag
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.hkdf import HKDF

NAME_PREFIX = "h0e1."
HEADER_SIZE = 80
TAG_SIZE = 16
CHUNK_SIZE = 4 * 1024 * 1024
MAGIC = b"H0E1"
MASTER_AAD = b"harbor0/e2ee/v1/master"
NAME_AAD = b"harbor0/e2ee/v1/name"


class E2eeError(Exception):
    pass


# ------------------------------------------------------------------ helpers

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


def to_b64url(b: bytes) -> str:
    return base64.urlsafe_b64encode(b).rstrip(b"=").decode("ascii")


def hkdf(secret: bytes, info: str, length: int = 32, salt: bytes = b"") -> bytes:
    """HKDF-SHA256. An empty salt means RFC 5869's default (32 zero bytes)."""
    return HKDF(
        algorithm=hashes.SHA256(), length=length, salt=salt or None, info=info.encode()
    ).derive(secret)


def _open(key: bytes, iv: bytes, sealed: bytes, aad: bytes) -> bytes:
    """AES-256-GCM open; `sealed` is the ciphertext followed by the 16-byte tag."""
    try:
        return AESGCM(key).decrypt(iv, sealed, aad)
    except InvalidTag:
        raise E2eeError("Wrong key, or the data was changed.") from None


def _seal(key: bytes, iv: bytes, plain: bytes, aad: bytes) -> bytes:
    return AESGCM(key).encrypt(iv, plain, aad)


# ----------------------------------------------------------- the master key

def unlock_with_passphrase(envelope: dict, passphrase: str) -> bytes:
    """Unwraps the account's 32-byte master key with the encryption passphrase."""
    kek = hash_secret_raw(
        secret=unicodedata.normalize("NFKC", passphrase).encode("utf-8"),
        salt=from_b64url(envelope["salt"]),
        time_cost=envelope["iterations"],
        memory_cost=envelope["memoryKiB"],
        parallelism=envelope["parallelism"],
        hash_len=32,
        type=Type.ID,
    )
    return _unwrap_master(kek, envelope)


def unlock_with_recovery(envelope: dict, recovery_key: str) -> bytes:
    """Unwraps the master key with the recovery key (e.g. "S33W-DHE4-...")."""
    recovery = parse_recovery_key(recovery_key)
    if recovery is None:
        raise E2eeError("That is not a recovery key.")
    kek = hkdf(recovery, "harbor0/e2ee/v1/recovery", 32, from_b64url(envelope["salt"]))
    return _unwrap_master(kek, envelope)


def _unwrap_master(kek: bytes, envelope: dict) -> bytes:
    master = _open(kek, from_b64url(envelope["iv"]), from_b64url(envelope["ciphertext"]), MASTER_AAD)
    if len(master) != 32:
        raise E2eeError("The stored key is damaged.")
    return master


def parse_recovery_key(typed: str) -> bytes | None:
    """Recovery keys are 20 bytes written as 32 Crockford base32 characters."""
    alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
    chars = re.sub(r"[\s-]", "", typed.upper()).replace("O", "0").replace("I", "1")
    chars = chars.replace("L", "1").replace("U", "V")
    if not re.fullmatch(r"[0-9A-HJKMNP-TV-Z]{32}", chars):
        return None
    value = int("".join(f"{alphabet.index(c):05b}" for c in chars), 2)
    return value.to_bytes(20, "big")


class AccountKeys:
    """The working keys, derived once from the master key."""

    def __init__(self, master: bytes):
        names = hkdf(master, "harbor0/e2ee/v1/names", 64)
        self.file_wrap = hkdf(master, "harbor0/e2ee/v1/file-keys")
        self.name_enc = names[:32]
        self.name_mac = names[32:]


# -------------------------------------------------------------------- names

def is_encrypted_name(name: str) -> bool:
    return re.fullmatch(r"h0e1\.[A-Za-z0-9_-]+", name) is not None


def decrypt_name(keys: AccountKeys, token: str) -> str:
    """"h0e1.…" → the real name."""
    data = from_b64url(token[len(NAME_PREFIX):])
    if len(data) < 12 + TAG_SIZE:
        raise E2eeError("The name is damaged.")
    return _open(keys.name_enc, data[:12], data[12:], NAME_AAD).decode("utf-8")


def encrypt_name(keys: AccountKeys, name: str) -> str:
    """The real name → "h0e1.…". The same name always gives the same token."""
    plain = unicodedata.normalize("NFC", name).encode("utf-8")
    if len(plain) > 255:
        raise E2eeError("Names on encrypted accounts are at most 255 bytes.")
    iv = hmac.new(keys.name_mac, plain, hashlib.sha256).digest()[:12]
    return NAME_PREFIX + to_b64url(iv + _seal(keys.name_enc, iv, plain, NAME_AAD))


# -------------------------------------------------------------------- files

def plain_size(stored: int, chunk_size: int = CHUNK_SIZE) -> int:
    """Size of the original file, from the stored (encrypted) size."""
    body = stored - HEADER_SIZE
    if body < TAG_SIZE:
        return 0
    return body - TAG_SIZE * math.ceil(body / (chunk_size + TAG_SIZE))


def encrypted_size(plain: int, chunk_size: int = CHUNK_SIZE) -> int:
    """Stored (encrypted) size of a file of `plain` bytes."""
    return HEADER_SIZE + plain + TAG_SIZE * max(1, math.ceil(plain / chunk_size))


class FileCipher:
    """One file version's content key, read from or written into its 80-byte header."""

    def __init__(self, content_key: bytes, bound: bytes):
        self.key = content_key
        self.bound = bound  # header[0:20]: magic, version, chunk size, nonce prefix
        self.chunk_size = struct.unpack(">I", bound[8:12])[0]

    @classmethod
    def open(cls, keys: AccountKeys, header: bytes) -> "FileCipher":
        if len(header) < HEADER_SIZE or header[:4] != MAGIC or header[4] != 1:
            raise E2eeError("Not an h0e1 encrypted file.")
        chunk = struct.unpack(">I", header[8:12])[0]
        if not 4096 <= chunk <= 64 * 1024 * 1024:
            raise E2eeError("Damaged header.")
        bound = bytes(header[:20])
        return cls(_open(keys.file_wrap, header[20:32], header[32:80], bound), bound)

    @classmethod
    def create(cls, keys: AccountKeys) -> tuple["FileCipher", bytes]:
        """A new random content key; returns the cipher and the 80-byte header to store first."""
        bound = MAGIC + bytes([1, 0, 0, 0]) + struct.pack(">I", CHUNK_SIZE) + os.urandom(8)
        content_key, wrap_iv = os.urandom(32), os.urandom(12)
        header = bound + wrap_iv + _seal(keys.file_wrap, wrap_iv, content_key, bound)
        return cls(content_key, bound), header

    def _nonce(self, index: int) -> bytes:
        return self.bound[12:20] + struct.pack(">I", index)

    def _aad(self, last: bool) -> bytes:
        return self.bound + (b"\x01" if last else b"\x00")

    def decrypt_chunk(self, index: int, sealed: bytes, last: bool) -> bytes:
        return _open(self.key, self._nonce(index), sealed, self._aad(last))

    def encrypt_chunk(self, index: int, plain: bytes, last: bool) -> bytes:
        return _seal(self.key, self._nonce(index), plain, self._aad(last))


def decrypt_stream(keys: AccountKeys, stored: BinaryIO, stored_size: int) -> Iterator[bytes]:
    """Reads a whole stored file (header first) and yields the original bytes, chunk by chunk."""
    cipher = FileCipher.open(keys, _read_exactly(stored, HEADER_SIZE))
    total = plain_size(stored_size, cipher.chunk_size)
    count = max(1, math.ceil(total / cipher.chunk_size))
    for i in range(count):
        length = min(cipher.chunk_size, total - i * cipher.chunk_size) + TAG_SIZE
        yield cipher.decrypt_chunk(i, _read_exactly(stored, length), i == count - 1)


def decrypt_file(keys: AccountKeys, stored: bytes) -> bytes:
    """Decrypts a whole stored file held in memory."""
    import io

    return b"".join(decrypt_stream(keys, io.BytesIO(stored), len(stored)))


def encrypt_stream(keys: AccountKeys, plain: BinaryIO, size: int) -> Iterator[bytes]:
    """Yields the stored bytes for a file of `size` bytes: the header, then each sealed chunk."""
    cipher, header = FileCipher.create(keys)
    yield header
    count = max(1, math.ceil(size / CHUNK_SIZE))
    for i in range(count):
        chunk = _read_exactly(plain, min(CHUNK_SIZE, size - i * CHUNK_SIZE))
        yield cipher.encrypt_chunk(i, chunk, i == count - 1)


def _read_exactly(f: BinaryIO, n: int) -> bytes:
    out = bytearray()
    while len(out) < n:
        data = f.read(n - len(out))
        if not data:
            raise E2eeError("The file ended early.")
        out += data
    return bytes(out)
