import random
from django.conf import settings


def get_prime():
    """Returns the prime modulus P from settings, or the default demo value."""
    return getattr(settings, 'ZKP_PRIME_P', 2695139)


def get_generator():
    """Returns the generator G from settings, or the default demo value."""
    return getattr(settings, 'ZKP_GENERATOR_G', 2)


class ZKPVerifier:
    """
    Implements the Verifier side of the Schnorr Interactive ZKP protocol.
    """

    @staticmethod
    def generate_challenge():
        """Step 2: Verifier generates a random challenge c."""
        return random.randint(1, get_prime() - 1)

    @staticmethod
    def verify_proof(public_key_y, commitment_t, challenge_c, response_s):
        """
        Step 4: Verifier checks g^s == t * y^c (mod p).

        Derivation:
            s = r + c*x  =>  g^s = g^r * (g^x)^c = t * y^c  (mod p)
        """
        p = get_prime()
        g = get_generator()
        lhs = pow(g, response_s, p)
        rhs = (commitment_t * pow(public_key_y, challenge_c, p)) % p
        return lhs == rhs


class ZKPProver:
    """
    Implements the Prover side (client) in Python — useful for tests and
    server-side simulations. In production the prover runs in the browser (JS).
    """

    @staticmethod
    def generate_private_key(password_hash_int):
        return password_hash_int % (get_prime() - 1)

    @staticmethod
    def generate_public_key(private_key_x):
        return pow(get_generator(), private_key_x, get_prime())
