from Crypto.Util.number import getPrime, bytes_to_long

with open('flag.txt','rb') as f:
    flag = f.read()

pulls = 50
pull_count = 0
coupon = b'Winning5050sFORFREE'

p = getPrime(1024)
q = getPrime(1024)
e = 65537

n = p*q
d = pow(e,-1,(p-1)*(q-1))
message = bytes_to_long(coupon)
ciphertext = pow(bytes_to_long(flag),e,n)



print(f'''
------------------------------------------------------------------------------------------------------
Welcome to the new and improved gacha system! Try your luck now :D

Current Number of Pulls: {pulls}
n = {n}
e = {e}
ciphertext = {ciphertext}

''')

while True:
    user_choice = int(input('''
Options:
1. Sign my super cool message
2. Enter a signature for my coupon
3. Try my luck
4. Exit

What will your choice be(1/2/3/4): '''))
    if user_choice == 1:
        user_message = int(input('Please input the message to sign: '))
        if user_message == message or user_message < 0 or user_message >= n or user_message == ciphertext:
            print('we cannot sign this message >:(')
        else:
            signed_message = pow(user_message,d,n)
            print(f'your signed message is: {signed_message}')
    elif user_choice == 2:
        input_signature = int(input('please input your signed message: '))
        signed_message = pow(input_signature,e,n)
        if signed_message == message:
            print("\n\nCoupon Redeemed!! here's your prize: ")
            pulls += 50
            print('pulls added: 50, here is your new pull count: ')
            print(f'Current Number of Pulls: {pulls}')
        else:
            print('stop trying to scam a 50/50 win out of me >:(')
    elif user_choice == 3:
        if pulls == 0:
            print('oops! out of pulls :(')
        elif pull_count == 90:
            print('hard pity reached! here is your p!')
            print(f'{p = }')
        else:
            random_p = getPrime(1024)
            print('here is a possible value of p:')
            print(f'p = {random_p}')
            pulls -= 1
            pull_count += 1
            print(f'remaining pulls: {pulls}')
    elif user_choice == 4:
        print('bye!')
        exit()
    else:
        print('invalid input')
