from seleniumwire import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import json
import sys

def add_to_basket_and_capture(headless=False):
    import platform
    
    # Detect OS
    is_linux = platform.system() == 'Linux'
    is_windows = platform.system() == 'Windows'
    
    # Chrome options
    chrome_options = Options()
    chrome_options.add_argument('--disable-blink-features=AutomationControlled')
    chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
    chrome_options.add_experimental_option('useAutomationExtension', False)
    
    # Force headless on Linux (VPS genelde GUI yok)
    if is_linux:
        headless = True
        print("[Linux] Forcing HEADLESS mode")
    
    # Headless mode if needed (for bot execution or Linux)
    if headless:
        chrome_options.add_argument('--headless=new')
        chrome_options.add_argument('--no-sandbox')
        chrome_options.add_argument('--disable-dev-shm-usage')
        chrome_options.add_argument('--disable-gpu')
        chrome_options.add_argument('--disable-software-rasterizer')
        chrome_options.add_argument('--disable-extensions')
        print("[BOT] Running in HEADLESS mode")
    else:
        print("[MANUAL] Running in GUI mode")
    
    # User agent
    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"
    chrome_options.add_argument(f'user-agent={user_agent}')
    
    # Linux-specific Chrome options
    if is_linux:
        chrome_options.add_argument('--remote-debugging-port=9222')
        
        # Try to find Chrome binary on Linux
        import os
        chrome_paths = [
            '/usr/bin/google-chrome',
            '/usr/bin/google-chrome-stable',
            '/usr/bin/chromium-browser',
            '/usr/bin/chromium',
            '/snap/bin/chromium'
        ]
        
        chrome_found = False
        for chrome_path in chrome_paths:
            if os.path.exists(chrome_path):
                chrome_options.binary_location = chrome_path
                print(f"[OK] Chrome found at: {chrome_path}")
                chrome_found = True
                break
        
        if not chrome_found:
            print("[WARNING] Chrome binary not found in standard locations")
    
    # Selenium Wire options (custom storage for Linux permissions)
    seleniumwire_options = {}
    if is_linux:
        import tempfile
        storage_dir = tempfile.mkdtemp(prefix='seleniumwire_')
        seleniumwire_options = {
            'request_storage_base_dir': storage_dir
        }
        print(f"[INFO] Using storage dir: {storage_dir}")
    
    # Selenium Wire ile driver başlat
    print("[START] Starting Chrome driver...")
    try:
        driver = webdriver.Chrome(options=chrome_options, seleniumwire_options=seleniumwire_options)
    except Exception as e:
        print(f"[ERROR] Chrome driver error: {e}")
        print("[INFO] Make sure Chrome/Chromium and chromedriver are installed:")
        if is_linux:
            print("   - sudo apt-get install chromium-browser chromium-chromedriver")
            print("   - OR: sudo apt-get install google-chrome-stable")
        else:
            print("   - Download from: https://chromedriver.chromium.org/")
        sys.exit(1)
    
    try:
        # Ürün sayfasına git
        url = "https://notjustashop.arts.ac.uk/product/orange-puffa-jacket-cat-felt-decoration/"
        print(f"[STEP 1] Navigating to product page: {url}")
        driver.get(url)
        
        # Sayfa yüklensin
        time.sleep(3)
        
        # Cookie popup'ını kapat
        try:
            cookie_buttons = [
                (By.ID, "ccc-recommended-settings"),
                (By.CSS_SELECTOR, "#ccc .ccc-close"),
                (By.CSS_SELECTOR, "button.ccc-accept"),
                (By.XPATH, "//button[contains(text(), 'Accept')]"),
                (By.XPATH, "//button[contains(text(), 'OK')]")
            ]
            
            for selector_type, selector in cookie_buttons:
                try:
                    cookie_btn = driver.find_element(selector_type, selector)
                    cookie_btn.click()
                    time.sleep(2)
                    break
                except:
                    continue
        except:
            pass
        
        # "Add to basket" butonunu bul ve tıkla
        try:
            print("[STEP 2] Adding product to basket...")
            add_button = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, "button[name='add-to-cart'][value='30021']"))
            )
            
            # JavaScript ile tıkla (overlay varsa bypass için)
            driver.execute_script("arguments[0].click();", add_button)
            
            # Sepete eklensin diye bekle
            time.sleep(3)
            print("[OK] Product added to basket")
            
            # Checkout sayfasına git
            print("[STEP 3] Navigating to checkout page...")
            del driver.requests
            
            driver.get("https://notjustashop.arts.ac.uk/checkout/")
            
            time.sleep(5)
            print("[OK] Checkout page loaded")
            
            # Cookie popup kapat (checkout sayfasında da olabilir)
            try:
                cookie_close = driver.find_element(By.ID, "ccc-recommended-settings")
                driver.execute_script("arguments[0].click();", cookie_close)
                time.sleep(2)
            except:
                pass
            
            # Kart bilgileri (default)
            card_number = "5269110181169311"
            card_exp = "12 2029"
            card_cvv = "001"
            
            print("[STEP 4] Filling payment information...")
            
            # Iframe'e geç ve kart bilgilerini gir
            # Card Number iframe
            card_number_iframe = driver.find_element(By.CSS_SELECTOR, "iframe[name='card-number']")
            driver.switch_to.frame(card_number_iframe)
            driver.find_element(By.ID, "secure-payment-field").send_keys(card_number)
            driver.switch_to.default_content()
            
            # Card Expiration iframe
            card_exp_iframe = driver.find_element(By.CSS_SELECTOR, "iframe[name='card-expiration']")
            driver.switch_to.frame(card_exp_iframe)
            driver.find_element(By.ID, "secure-payment-field").send_keys(card_exp)
            driver.switch_to.default_content()
            
            # Card CVV iframe
            card_cvv_iframe = driver.find_element(By.CSS_SELECTOR, "iframe[name='card-cvv']")
            driver.switch_to.frame(card_cvv_iframe)
            driver.find_element(By.ID, "secure-payment-field").send_keys(card_cvv)
            driver.switch_to.default_content()
            
            # Card Holder Name iframe
            card_holder_iframe = driver.find_element(By.CSS_SELECTOR, "iframe[name='card-holder-name']")
            driver.switch_to.frame(card_holder_iframe)
            driver.find_element(By.ID, "secure-payment-field").send_keys("aasd asdasd")
            driver.switch_to.default_content()
            
            time.sleep(2)
            
            # Terms checkbox'ı tıkla
            terms_checkbox = driver.find_element(By.ID, "terms")
            driver.execute_script("arguments[0].click();", terms_checkbox)
            
            time.sleep(2)
            
            # Mailchimp popup kapat
            try:
                mailchimp_close = driver.find_element(By.CSS_SELECTOR, ".mc-closeModal")
                driver.execute_script("arguments[0].click();", mailchimp_close)
                time.sleep(2)
            except:
                pass
            
            # Store notice/banner'ı kapat (submit'i engelliyor olabilir)
            try:
                store_notice = driver.find_element(By.CSS_SELECTOR, ".woocommerce-store-notice.demo_store")
                driver.execute_script("arguments[0].style.display='none';", store_notice)
                print("[INFO] Store notice hidden")
            except:
                pass
            
            # Place Order butonuna bas ve istekleri yakala
            print("[STEP 5] Submitting payment (capturing API token)...")
            # Submit iframe
            submit_iframe = driver.find_element(By.CSS_SELECTOR, "iframe[name='submit']")
            driver.switch_to.frame(submit_iframe)
            submit_button = driver.find_element(By.ID, "secure-payment-field")
            
            # JavaScript ile tıkla (overlay bypass için)
            driver.execute_script("arguments[0].click();", submit_button)
            driver.switch_to.default_content()
            
            time.sleep(5)
            print("[WAIT] Waiting for API request...")
            
            # Sadece globalpay API isteğini bul
            target_url = "https://apis.globalpay.com/ucp/payment-methods"
            found = False
            auth_token = None
            
            for request in driver.requests:
                if target_url in request.url and request.response:
                    found = True
                    
                    for key, value in request.headers.items():
                        if key.lower() == 'authorization':
                            auth_token = value.replace("Bearer ", "").strip()
                    
                    # Token'ı dosyaya kaydet
                    if auth_token:
                        with open("vbvapitoken.txt", "w") as f:
                            f.write(auth_token)
                        print(f"[SUCCESS] API Token saved: {auth_token[:50]}...")
                    
                    break
            
            if not found:
                print("[ERROR] API token not found in requests!")
                if headless:
                    driver.quit()
                    sys.exit(1)
            
            # Bot çalıştırıyorsa tarayıcıyı kapat, manual ise açık tut
            if headless:
                print("[SUCCESS] Token captured successfully! Closing browser...")
                time.sleep(2)
                driver.quit()
                
                # Clean up temp directory on Linux
                if is_linux and 'storage_dir' in locals():
                    import shutil
                    try:
                        shutil.rmtree(storage_dir)
                        print("[CLEANUP] Temp storage removed")
                    except:
                        pass
                
                print("[DONE] Process completed successfully!")
                sys.exit(0)
            else:
                print("\n[SUCCESS] Token captured! Browser will stay open for inspection.")
                print("Press Ctrl+C to close...")
                # Tarayıcıyı açık tut
                while True:
                    time.sleep(1)
            
        except Exception as e:
            print(f"[ERROR] Exception: {e}")
            if headless:
                driver.quit()
                
                # Clean up temp directory on Linux
                if is_linux and 'storage_dir' in locals():
                    import shutil
                    try:
                        shutil.rmtree(storage_dir)
                    except:
                        pass
                
                sys.exit(1)
            
    except KeyboardInterrupt:
        print("\n\n[!] Kapatılıyor...")
    except Exception as e:
        print(f"\n[ERROR] Exception: {e}")
    finally:
        driver.quit()

if __name__ == "__main__":
    import sys
    
    # Check if running from bot (headless mode)
    headless_mode = '--headless' in sys.argv or len(sys.argv) == 1
    
    # If called with arguments, assume it's from bot
    if len(sys.argv) > 1 and sys.argv[0].endswith('python') or sys.argv[0].endswith('python.exe'):
        headless_mode = True
    
    print("=" * 50)
    print("VBV TOKEN REFRESH - GlobalPay API")
    print("=" * 50)
    
    add_to_basket_and_capture(headless=headless_mode)
