import hashlib
import json
import random

FLAG = b"crypto{???????????????????????????????}"

N = 256
Q = 12289
EXP = 13371337


def find_primitive_2n_root(n: int, q: int) -> int:
    for psi in range(2, q):
        if pow(psi, n, q) == q - 1:
            return psi
    raise ValueError("No primitive 2n-th root of unity found.")


def cyclic_ntt(a: list[int], q: int, root: int) -> list[int]:
    n = len(a)
    res = a[:]
    j = 0
    for i in range(1, n):
        bit = n >> 1
        while j & bit:
            j ^= bit
            bit >>= 1
        j ^= bit
        if i < j:
            res[i], res[j] = res[j], res[i]

    length = 2
    while length <= n:
        wlen = pow(root, n // length, q)
        half = length >> 1
        for i in range(0, n, length):
            w = 1
            for k in range(half):
                u = res[i + k]
                v = (res[i + k + half] * w) % q
                res[i + k] = (u + v) % q
                res[i + k + half] = (u - v) % q
                w = (w * wlen) % q
        length <<= 1
    return res


def negacyclic_ntt(a: list[int], q: int, psi: int) -> list[int]:
    n = len(a)
    omega = (psi * psi) % q
    twisted = [(a[i] * pow(psi, i, q)) % q for i in range(n)]
    return cyclic_ntt(twisted, q, omega)


def negacyclic_intt(a_hat: list[int], q: int, psi: int) -> list[int]:
    n = len(a_hat)
    psi_inv = pow(psi, -1, q)
    omega_inv = (psi_inv * psi_inv) % q
    n_inv = pow(n, -1, q)
    twisted = cyclic_ntt(a_hat, q, omega_inv)
    return [(twisted[i] * n_inv * pow(psi_inv, i, q)) % q for i in range(n)]


def encrypt_flag(flag: bytes, secret_poly: list[int]) -> str:
    key = hashlib.sha256(json.dumps(secret_poly).encode()).digest()
    stream = b""
    counter = 0
    while len(stream) < len(flag):
        stream += hashlib.sha256(key + counter.to_bytes(4, "big")).digest()
        counter += 1
    return bytes(a ^ b for a, b in zip(flag, stream)).hex()


def main():
    psi = find_primitive_2n_root(N, Q)
    rng = random.Random(2026)
    A = [rng.randrange(Q) for _ in range(N)]
    B = [rng.randrange(Q) for _ in range(N)]

    A_hat = negacyclic_ntt(A, Q, psi)
    B_hat = negacyclic_ntt(B, Q, psi)
    C_hat = [(pow(a, EXP, Q) * b) % Q for a, b in zip(A_hat, B_hat)]
    C = negacyclic_intt(C_hat, Q, psi)

    output = {
        "n": N,
        "q": Q,
        "psi": psi,
        "exp": EXP,
        "A": A,
        "B": B,
        "enc_flag": encrypt_flag(FLAG, C),
    }

    with open("output.txt", "w") as f:
        json.dump(output, f)

    print("Generated output.txt.")


if __name__ == "__main__":
    main()
    