"""Run with Python and TenSEAL 0.3.18."""
from time import perf_counter

import tenseal as ts

values = [1.5, -2.0, 0.25]
weights = [2.0, 0.5, 4.0]
expected = sum(x * w for x, w in zip(values, weights))

owner = ts.context(
    ts.SCHEME_TYPE.CKKS,
    poly_modulus_degree=8192,
    coeff_mod_bit_sizes=[60, 40, 40, 60],
)
owner.global_scale = 2**40
owner.generate_galois_keys()

encrypted_input = ts.ckks_vector(owner, values).serialize()
evaluation_context = ts.context_from(owner.serialize(save_secret_key=False))
assert not evaluation_context.has_secret_key()
ciphertext = ts.ckks_vector_from(evaluation_context, encrypted_input)

start = perf_counter()
encrypted_result = ciphertext.dot(weights)
elapsed_ms = (perf_counter() - start) * 1000

result_bytes = encrypted_result.serialize()
actual = ts.ckks_vector_from(owner, result_bytes).decrypt()[0]
error = abs(actual - expected)
assert error < 1e-4

print(f"Plaintext: {expected:.6f}")
print(f"Decrypted: {actual:.9f}")
print(f"Absolute error: {error:.3g}")
print(f"Input / output bytes: {len(encrypted_input)} / {len(result_bytes)}")
print(f"Evaluation only: {elapsed_ms:.3f} ms")
input_primes = ciphertext.ciphertext()[0].coeff_modulus_size()
result_primes = encrypted_result.ciphertext()[0].coeff_modulus_size()
print(f"Input / output coefficient modulus primes: {input_primes} / {result_primes}")
