from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.microsoft import EdgeChromiumDriverManager
import time
import os
import tempfile

# تحديد مسار التحميل
download_path = r"/home/ubuntu/TARequisitions"
# إنشاء المجلد إذا لم يكن موجوداً
if not os.path.exists(download_path):
    os.makedirs(download_path)
    print(f"Created download directory: {download_path}")

# Configure Edge browser options
edge_options = Options()
edge_options.add_argument("--start-maximized")
edge_options.add_argument("--disable-notifications")
edge_options.add_argument("--disable-blink-features=AutomationControlled")
edge_options.add_experimental_option("excludeSwitches", ["enable-automation"])
edge_options.add_argument("--headless=new")  # للنسخ الحديثة من Edge/Chromium

# مجلد مؤقت لكل جلسة لتجنب المشاكل
user_data_dir = tempfile.mkdtemp()
edge_options.add_argument(f"--user-data-dir={user_data_dir}")
# إعداد خيارات التحميل
prefs = {
    "download.default_directory": download_path,
    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "safebrowsing.enabled": True
}
edge_options.add_experimental_option("prefs", prefs)

# مسار السائق (driver)
driver_path = r"/home/ubuntu/edgedriver_linux64/msedgedriver"

# Login credentials (use environment variables in production!)
EMAIL = os.getenv("ZOHO_EMAIL", "ahmed.abdelfattah@future-group.com")
PASSWORD = os.getenv("ZOHO_PASSWORD", "MoDy*855913")

def find_and_click_export_button(driver, attempts=3):
    """Click the export button using the specified XPath, starting with iframe 2"""
    for attempt in range(attempts):
        print(f"Attempt {attempt + 1} to find export button...")

        # البحث مباشرة في iframe 2 (الذي نجح من قبل)
        try:
            print("Searching directly in iframe 2...")
            frames = driver.find_elements(By.TAG_NAME, 'iframe')
            print(f"Found {len(frames)} iframes")

            if len(frames) >= 2:
                # الانتقال مباشرة إلى iframe 2 (index 1)
                driver.switch_to.frame(frames[1])
                print("Switched to iframe 2")

                # البحث عن زر التصدير
                export_btn = WebDriverWait(driver, 10).until(
                    EC.element_to_be_clickable((By.XPATH, '/html/body/div[12]/div[16]/div/div[1]/div[1]/div[1]/div[1]/div/button[1]'))
                )
                driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", export_btn)
                time.sleep(1)
                driver.execute_script("arguments[0].click();", export_btn)
                print("Successfully clicked export button in iframe 2")

                # انتظار ظهور القائمة المنسدلة والنقر على خيار CSV
                time.sleep(2)
                csv_option = WebDriverWait(driver, 10).until(
                    EC.element_to_be_clickable((By.XPATH, '//*[@id="dropDownMenu"]/ul/li[1]'))
                )
                driver.execute_script("arguments[0].click();", csv_option)
                print("Successfully clicked CSV export option in iframe 2")
                return True
            else:
                print("iframe 2 not found, falling back to search all iframes")

        except Exception as e:
            print(f"iframe 2 direct access failed: {str(e)}")
            driver.switch_to.default_content()

        # إذا فشل iframe 2، ابحث في جميع الـ iframes كما كان من قبل
        print("Searching in all iframes...")
        frames = driver.find_elements(By.TAG_NAME, 'iframe')

        for i, frame in enumerate(frames):
            try:
                print(f"Checking iframe {i+1}...")
                driver.switch_to.frame(frame)

                # محاولة البحث بـ XPath المحدد أولاً
                try:
                    export_btn = WebDriverWait(driver, 5).until(
                        EC.element_to_be_clickable((By.XPATH, '/html/body/div[12]/div[16]/div/div[1]/div[1]/div[1]/div[1]/div/button[1]'))
                    )
                    driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", export_btn)
                    time.sleep(1)
                    driver.execute_script("arguments[0].click();", export_btn)
                    print(f"Successfully clicked export button in iframe {i+1} using specified XPath")
                except:
                    # محاولة البحث بطرق أخرى
                    alternative_selectors = [
                        (By.ID, 'ZDBExportButton'),
                        (By.XPATH, '//button[contains(@id, "ExportButton")]'),
                        (By.XPATH, '//button[contains(text(), "Export")]'),
                        (By.XPATH, '//button[contains(@class, "export")]')
                    ]

                    export_btn = None
                    for by, selector in alternative_selectors:
                        try:
                            export_btn = WebDriverWait(driver, 3).until(
                                EC.element_to_be_clickable((by, selector))
                            )
                            driver.execute_script("arguments[0].scrollIntoView({block: 'center'});", export_btn)
                            time.sleep(1)
                            driver.execute_script("arguments[0].click();", export_btn)
                            print(f"Successfully clicked export button in iframe {i+1} using {selector}")
                            break
                        except:
                            continue

                    if export_btn is None:
                        raise Exception("No export button found with any selector")

                # انتظار ظهور القائمة المنسدلة والنقر على خيار CSV
                time.sleep(2)
                csv_option = WebDriverWait(driver, 10).until(
                    EC.element_to_be_clickable((By.XPATH, '//*[@id="dropDownMenu"]/ul/li[1]'))
                )
                driver.execute_script("arguments[0].click();", csv_option)
                print("Successfully clicked CSV export option in iframe")
                return True

            except Exception as e:
                print(f"Iframe {i+1} failed: {str(e)}")
                driver.switch_to.default_content()
                continue

        # العودة للصفحة الرئيسية
        driver.switch_to.default_content()
        print(f"Attempt {attempt + 1} completed, waiting before next attempt...")
        time.sleep(5)  # انتظار قبل المحاولة التالية

    return False

try:
    # إنشاء الـ WebDriver باستخدام Service و Options
    service = Service(driver_path)
    driver = webdriver.Edge(service=service, options=edge_options)

    # تغيير الـ User-Agent
    driver.execute_cdp_cmd("Network.setUserAgentOverride", {
        "userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.60"
    })

    # Load Zoho page
    print("Loading Zoho page...")
    driver.get("https://one.zoho.com/zohoone/kalamportal/home/cxapp/recruit/kalam/Analytics.do?subTab=Reports&action=run&actionItem=run&reportId=778184000009009056&repType=summary&folderId=778184000009195396")
    time.sleep(3)

    # Handle cookies popup if it appears
    try:
        cookie_btn = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, '//button[contains(text(), "Accept")]'))
        )
        cookie_btn.click()
        print("Cookies accepted")
    except:
        print("No cookies popup found")

    # Login process
    print("Entering email...")
    email_field = WebDriverWait(driver, 25).until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, 'input#login_id'))
    )
    email_field.clear()
    email_field.send_keys(EMAIL)

    print("Clicking next button...")
    next_btn = WebDriverWait(driver, 25).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, 'button#nextbtn'))
    )
    next_btn.click()

    time.sleep(3)  # Wait for password page to load

    print("Entering password...")
    password_field = WebDriverWait(driver, 25).until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, 'input#password'))
    )
    password_field.clear()
    password_field.send_keys(PASSWORD)

    print("Logging in...")
    login_btn = WebDriverWait(driver, 25).until(
        EC.element_to_be_clickable((By.CSS_SELECTOR, 'button#nextbtn'))
    )
    login_btn.click()

    # Verify successful login
    WebDriverWait(driver, 30).until(
        lambda d: "dashboard" in d.current_url.lower() or "home" in d.current_url.lower()
    )
    print("✅ Successfully logged in to Zoho!")

    # Wait for full page load
    time.sleep(5)

    # Attempt to find and click export button
    if find_and_click_export_button(driver):
        print("Export process initiated...")

        # Wait for export dialog to appear
        time.sleep(3)

        # Click the final confirmation button after export
        try:
            final_button = WebDriverWait(driver, 20).until(
                EC.element_to_be_clickable((By.XPATH, '/html/body/div[17]/div/div[2]/div/footer/div/div[2]/button[1]'))
            )
            final_button.click()
            print("Clicked the final confirmation button")
        except Exception as e:
            print(f"Failed to click final confirmation button: {str(e)}")

        # Wait for export to complete
        time.sleep(5)
        print("✅ File downloaded successfully!")
        print(f"📁 File saved to: {download_path}")
    else:
        print("❌ Failed to find export button after multiple attempts")

except Exception as e:
    print(f"❌ Execution failed: {str(e)}")
    driver.save_screenshot('zoho_error.png')
    print("Screenshot saved as 'zoho_error.png'")

finally:
    print("Closing browser automatically...")
    time.sleep(3)  # انتظار 3 ثوان قبل إغلاق المتصفح
    driver.quit()
    print("Browser closed successfully!")