import time
import sys
import logging
import undetected_chromedriver as uc
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import WebDriverException, TimeoutException
from pyvirtualdisplay import Display

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("login_test.log", mode='w', encoding='utf-8'),
        logging.StreamHandler(sys.stdout)
    ]
)


def debug_submit_button(driver):
    """Debug function to inspect the submit button element"""
    try:
        wait = WebDriverWait(driver, 10)

        # Try to find the button and get its properties
        try:
            submit_button = wait.until(EC.presence_of_element_located((By.ID, "send2")))
            logging.info("Submit button found!")
            logging.info(f"Button tag name: {submit_button.tag_name}")
            logging.info(f"Button text: {submit_button.text}")
            logging.info(f"Button is displayed: {submit_button.is_displayed()}")
            logging.info(f"Button is enabled: {submit_button.is_enabled()}")
            logging.info(f"Button location: {submit_button.location}")
            logging.info(f"Button size: {submit_button.size}")

            # Get all attributes
            attributes = driver.execute_script(
                "var items = {}; "
                "for (index = 0; index < arguments[0].attributes.length; ++index) { "
                "items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; "
                "return items;", submit_button)
            logging.info(f"Button attributes: {attributes}")

        except Exception as e:
            logging.error(f"Could not find submit button: {e}")

            # Try to find all buttons on the page
            buttons = driver.find_elements(By.TAG_NAME, "button")
            logging.info(f"Found {len(buttons)} buttons on the page:")
            for i, btn in enumerate(buttons):
                try:
                    logging.info(
                        f"Button {i}: text='{btn.text}', id='{btn.get_attribute('id')}', class='{btn.get_attribute('class')}'")
                except:
                    logging.info(f"Button {i}: Could not get attributes")

            # Try to find all input elements with type submit
            submit_inputs = driver.find_elements(By.XPATH, "//input[@type='submit']")
            logging.info(f"Found {len(submit_inputs)} submit inputs on the page:")
            for i, inp in enumerate(submit_inputs):
                try:
                    logging.info(
                        f"Submit input {i}: value='{inp.get_attribute('value')}', id='{inp.get_attribute('id')}', class='{inp.get_attribute('class')}'")
                except:
                    logging.info(f"Submit input {i}: Could not get attributes")

    except Exception as e:
        logging.error(f"Debug function failed: {e}", exc_info=True)


def try_single_method(driver, email, password, method_name, method_function):
    """Try a single login method and check if it worked"""
    try:
        wait = WebDriverWait(driver, 20)

        # Fill in credentials
        email_field = wait.until(EC.presence_of_element_located((By.ID, "email")))
        email_field.clear()
        email_field.send_keys(email)

        # Try both "password" and "pass" IDs for password field
        pass_field = None
        try:
            pass_field = driver.find_element(By.ID, "password")
        except:
            try:
                pass_field = driver.find_element(By.ID, "pass")
            except:
                logging.error("Could not find password field with either 'password' or 'pass' ID")
                return False

        pass_field.clear()
        pass_field.send_keys(password)
        time.sleep(2)

        # Get current URL before attempting to submit
        url_before = driver.current_url
        logging.info(f"URL before {method_name}: {url_before}")

        # Execute the method
        logging.info(f"Attempting {method_name}")
        method_function(driver, pass_field)
        logging.info(f"{method_name} - Click executed")

        # Wait for page to load and check result
        time.sleep(8)
        current_url = driver.current_url
        logging.info(f"URL after {method_name}: {current_url}")

        # Check if login was successful
        if current_url == 'https://b2bstore.if-sports.de/blog/' or 'blog' in current_url:
            logging.info(f"✅ Login successful using: {method_name}")

            # Get cookies
            cookies = driver.get_cookies()
            for cookie in cookies:
                if cookie['name'] == 'PHPSESSID':
                    phpsessid = cookie['value']
                    logging.info(f"PHPSESSID: {phpsessid}")
                    break

            return True
        else:
            logging.warning(f"❌ {method_name} failed - Login unsuccessful")
            return False

    except Exception as e:
        logging.warning(f"❌ {method_name} failed with exception: {e}")
        return False


def try_login_methods(driver, email, password):
    """Try multiple login methods until one works"""

    # Define all methods to try
    methods = [
        ("Method 1: WebDriverWait + click()",
         lambda d, p: WebDriverWait(d, 20).until(EC.element_to_be_clickable((By.ID, "send2"))).click()),

        ("Method 2: JavaScript click by ID",
         lambda d, p: d.execute_script("document.getElementById('send2').click();")),

        ("Method 3: ActionChains click",
         lambda d, p: ActionChains(d).move_to_element(d.find_element(By.ID, "send2")).click().perform()),

        ("Method 4: JavaScript querySelector",
         lambda d, p: d.execute_script("document.querySelector('#send2').click();")),

        ("Method 5: Button tag selector",
         lambda d, p: d.find_element(By.TAG_NAME, "button").click()),

        ("Method 6: XPath selector",
         lambda d, p: d.find_element(By.XPATH, "//button[@id='send2']").click()),

        ("Method 7: Form submit",
         lambda d, p: d.find_element(By.TAG_NAME, "form").submit()),

        ("Method 8: Enter key on password field",
         lambda d, p: p.send_keys(Keys.RETURN)),
    ]

    # Try each method
    for method_name, method_function in methods:
        # Refresh page for each attempt (except the first one)
        if method_name != "Method 1: WebDriverWait + click()":
            logging.info("Refreshing page for next attempt...")
            driver.refresh()
            time.sleep(3)

        success = try_single_method(driver, email, password, method_name, method_function)

        if success:
            return True, method_name

        logging.info(f"Moving to next method...\n")

    logging.error("All methods failed!")
    return False, None


def login():
    """Main function to test login"""
    display = None
    driver = None

    try:
        # Start virtual display (for headless environment)
        display = Display(visible=0, size=(1280, 720))
        display.start()
        logging.info("Virtual display started")

        # Setup Chrome driver
        options = uc.ChromeOptions()
        driver_path = '/home/Script/chromedriver'
        options.binary_location = "/usr/bin/google-chrome"

        # Add some options for better stability
        options.add_argument('--no-sandbox')
        options.add_argument('--disable-dev-shm-usage')
        options.add_argument('--disable-gpu')

        driver = uc.Chrome(driver_executable_path=driver_path, options=options)
        logging.info("Chrome driver initialized")

        # Navigate to login page
        login_url = 'https://b2bstore.if-sports.de/customer/account/login/'
        logging.info(f"Navigating to: {login_url}")
        driver.get(login_url)

        # Wait for page to load
        time.sleep(5)
        logging.info(f"Current URL: {driver.current_url}")
        logging.info(f"Page title: {driver.title}")

        # Debug the submit button
        debug_submit_button(driver)

        # Credentials
        b2b_email = 'info@fitnesspro.gr'
        b2b_pass = 'SdYfqm4rmJHoddbgCrY0'

        # Try login
        success, method = try_login_methods(driver, b2b_email, b2b_pass)

        if success:
            logging.info(f"🎉 LOGIN SUCCESS! Working method: {method}")

            # Take a screenshot of successful login (optional)
            try:
                driver.save_screenshot("successful_login.png")
                logging.info("Screenshot saved as successful_login.png")
            except:
                pass

        else:
            logging.error(f"💥 LOGIN FAILED! Last attempted method: {method}")

            # Take a screenshot of failed login for debugging
            try:
                driver.save_screenshot("failed_login.png")
                logging.info("Screenshot saved as failed_login.png")
            except:
                pass

        return success, method

    except Exception as e:
        logging.error(f"Test login failed: {e}", exc_info=True)
        return False, None

    finally:
        # Cleanup
        if driver:
            try:
                driver.quit()
                logging.info("Driver closed")
            except:
                pass

        if display:
            try:
                display.stop()
                logging.info("Display stopped")
            except:
                pass


if __name__ == "__main__":
    logging.info("=== LOGIN TEST PROGRAM STARTED ===")
    success, method = login()

    if success:
        print(f"\n✅ SUCCESS! Use this method in your main program: {method}")
    else:
        print(f"\n❌ FAILED! Check the logs for details.")

    logging.info("=== LOGIN TEST PROGRAM FINISHED ===")