from jwcrypto import jwk, jwe
import json, time, uuid, base64, requests
import jwt 
import hmac
import hashlib


MERC_ID = "BDUAT2K676"          
CLIENT_ID = "bduat2k676sj"     
KEY_ID = "vstkEu52BWR9"            

ENCRYPTION_KEY = b"e9Y5khgyMyluQRrH4XjgQLgZ9oZdwwk2"
SIGNING_KEY = "5ZvlXPsYeuk6VTJRlB5HyBOMpb4wPYQJ".encode()




payload = {
    "orderid": f"TEST{int(time.time())}",
    "mercid": MERC_ID,
    "order_date": time.strftime("%Y-%m-%dT%H:%M:%S+05:30"),
    "amount": "29999.28",
    "currency": "356",
    "ru": "https://www.merchant.com",
    "itemcode": "DIRECT",
    "device": {
        "init_channel": "internet",
        "ip": "123.0.0.1",
        "user_agent": "Mozilla/5.0",
        "accept_header": "application/json"
    }
}

# signature = hmac.new(SIGNING_KEY, payload.encode(), hashlib.sha256).digest()
signature = hmac.new(SIGNING_KEY, json.dumps(payload, separators=(',', ':')).encode(), hashlib.sha256).digest()

encoded_signature = base64.b64encode(signature).decode()


# Final Authorization header
auth_header = f"BDUAYUHDST2K676|{encoded_signature}"
print(auth_header)
print("0000000000000000000000000000000000000000000000000")




key_b64 = base64.urlsafe_b64encode(ENCRYPTION_KEY).decode()
key = jwk.JWK(k=key_b64, kty='oct')


payload = {
    "orderid": f"TEST{int(time.time())}",
    "mercid": MERC_ID,
    "order_date": time.strftime("%Y-%m-%dT%H:%M:%S+05:30"),
    "amount": "29999.28",
    "currency": "356",
    "ru": "https://www.merchant.com",
    "itemcode": "DIRECT",
    "device": {
        "init_channel": "internet",
        "ip": "123.0.0.1",
        "user_agent": "Mozilla/5.0",
        "accept_header": "application/json"
    }
}

# JWE header
protected_header = {
    "alg": "dir",
    "enc": "A256GCM",
    "kid": KEY_ID,
    "clientid": CLIENT_ID
}

# Encrypt
jwetoken = jwe.JWE(plaintext=json.dumps(payload).encode(), protected=protected_header)
jwetoken.add_recipient(key)
encrypted_payload = jwetoken.serialize()
print(encrypted_payload)
print("haaaaaaaaaaaaa")
API_URL = "https://uat1.billdesk.com/u2/payments/ve1_2/orders/create"

headers = {
    "Content-Type": "application/jose",
    "Accept": "application/jose",
    "BD-Traceid": str(uuid.uuid4()).replace("-", "")[:20],
    "BD-Timestamp": str(int(time.time()))
}

response = requests.post(API_URL, headers=headers, data=encrypted_payload)

print("Status Code:", response.status_code)
print("Response text:", response.text[:1000])

SIGNING_KEY = "5ZvlXPsYeuk6VTJRlB5HyBOMpb4wPYQJ"

try:
    decoded = jwt.decode(response.text, SIGNING_KEY, algorithms=["HS256"])
    print("Decoded response:", decoded)
except Exception as e:
    print("Could not decode response JWT:", str(e))
