"""Checks harbor0_e2ee.py against the published test vectors:
    python3 verify_vectors.py ../test-vectors.json
"""
import hashlib
import io
import json
import sys
import unicodedata
from pathlib import Path

import harbor0_e2ee as e2ee

v = json.loads(Path(sys.argv[1] if len(sys.argv) > 1 else Path(__file__).parent.parent / "test-vectors.json").read_text())
pattern = lambda n: bytes(i * 7 % 251 for i in range(n))
master = e2ee.from_b64url(v["master"])

assert e2ee.unlock_with_passphrase(v["passphrase"], v["passphraseText"]) == master
assert e2ee.unlock_with_recovery(v["recoveryEnv"], v["recovery"]) == master
assert e2ee.unlock_with_recovery(v["recoveryEnv"], v["recovery"].lower().replace("-", " ")) == master
try:
    e2ee.unlock_with_passphrase(v["passphrase"], "wrong")
    raise AssertionError("a wrong passphrase unlocked")
except e2ee.E2eeError:
    pass
print("ok  master key: passphrase and recovery key")

keys = e2ee.AccountKeys(master)
for plain, token in v["names"].items():
    assert e2ee.decrypt_name(keys, token) == unicodedata.normalize("NFC", plain)
    assert e2ee.encrypt_name(keys, plain) == token
print("ok  names: decrypt and encrypt", len(v["names"]))

for which in ("small", "empty"):
    stored = e2ee.from_b64url(v[which])
    plain = e2ee.decrypt_file(keys, stored)
    assert plain == pattern(e2ee.plain_size(len(stored)))
    print(f'ok  file "{which}": {len(plain)} bytes')

header = e2ee.from_b64url(v["bigHeader"])
cipher = e2ee.FileCipher.open(keys, header)
plain = pattern(v["bigSize"])
count = -(-len(plain) // cipher.chunk_size)
chunks = [header] + [
    cipher.encrypt_chunk(i, plain[i * cipher.chunk_size:(i + 1) * cipher.chunk_size], i == count - 1)
    for i in range(count)
]
stored = b"".join(chunks)
assert len(stored) == e2ee.encrypted_size(v["bigSize"])
assert hashlib.sha256(stored).hexdigest() == v["bigSha256"]
assert chunks[-1] == e2ee.from_b64url(v["bigLastChunk"])
assert e2ee.decrypt_file(keys, stored) == plain
print(f'ok  file "big": {v["bigSize"]} bytes in {count} chunks, stored SHA-256 matches')

again = b"".join(e2ee.encrypt_stream(keys, io.BytesIO(plain), len(plain)))
assert e2ee.decrypt_file(keys, again) == plain
print("ok  encrypt_stream round trip")
