from utils import listener
import math
import random

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

N = 32
Q = 12289
MAX_NORM = 600.0


def poly_mul(a, b):
    n = len(a)
    res = [0] * n
    for i in range(n):
        for j in range(n):
            if i + j < n:
                res[i + j] += a[i] * b[j]
            else:
                res[i + j - n] -= a[i] * b[j]
    return res


def poly_sub(a, b):
    return [x - y for x, y in zip(a, b)]


def field_norm(a):
    n2 = len(a) // 2
    ae = [a[2 * i] for i in range(n2)]
    ao = [a[2 * i + 1] for i in range(n2)]
    ae_sq = poly_mul(ae, ae)
    ao_sq = poly_mul(ao, ao)
    x_ao_sq = [-ao_sq[-1]] + ao_sq[:-1]
    return poly_sub(ae_sq, x_ao_sq)


def has_ntru_solution(f, g):
    while len(f) > 1:
        f = field_norm(f)
        g = field_norm(g)
    return math.gcd(abs(f[0]), abs(g[0])) == 1


def generate_fg(n, seed=2026):
    rng = random.Random(seed)
    while True:
        f = [rng.randint(-15, 15) for _ in range(n)]
        g = [rng.randint(-15, 15) for _ in range(n)]
        if has_ntru_solution(f, g):
            return f, g


def verify_solution(f, g, F, G):
    if not (isinstance(F, list) and isinstance(G, list) and len(F) == N and len(G) == N):
        return False, f"F and G must be lists of {N} integers."
    if not all(isinstance(x, int) for x in F + G):
        return False, "All coefficients must be integers."

    lhs = poly_sub(poly_mul(f, G), poly_mul(g, F))
    expected = [Q] + [0] * (N - 1)
    if lhs != expected:
        return False, "NTRU equation f*G - g*F = q does not hold."

    norm = math.sqrt(sum(x * x for x in F) + sum(x * x for x in G))
    if norm > MAX_NORM:
        return False, f"Solution is too long: ||(F, G)||_2 = {norm:.2f} > {MAX_NORM}."

    return True, FLAG


F_SECRET, G_SECRET = generate_fg(N)


class Challenge:
    def __init__(self):
        self.before_input = (
            f"Complete my NTRU basis: {{\"n\": {N}, \"q\": {Q}, \"max_norm\": {MAX_NORM}, \"f\": {F_SECRET}, \"g\": {G_SECRET}}}\n"
            f"Send your solution as JSON: {{\"F\": [...], \"G\": [...]}}\n"
        )
        self.max_payload_size = 16384

    def challenge(self, your_input):
        if "F" not in your_input or "G" not in your_input:
            return {"error": "You must provide F and G"}

        ok, msg = verify_solution(F_SECRET, G_SECRET, your_input["F"], your_input["G"])
        if ok:
            self.exit = True
            return {"flag": msg}
        return {"error": msg}


import builtins; builtins.Challenge = Challenge # hack to enable challenge to be run locally, see https://cryptohack.org/faq/#listener
listener.start_server(port=13440)
