from selenium import webdriver
from selenium.webdriver.chrome.service import Service
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.common.exceptions import TimeoutException, ElementClickInterceptedException
from selenium.webdriver.common.keys import Keys
import time
import logging

# Configuration paths
CHROMEDRIVER_PATH = 'C:/Program Files/chromedriver-win64/chromedriver.exe'
CANARY_BINARY_PATH = 'C:/Users/cazan/AppData/Local/Google/Chrome SxS/Application/chrome.exe'
USER_DATA_DIR = 'C:/Users/cazan/AppData/Local/Google/Chrome SxS/User Data'

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler("facebook_test.log", encoding="utf-8")
    ]
)

def wait_and_find_element(bot, by, value, timeout=30, message=""):
    """Helper function to wait for and find elements with better error handling"""
    try:
        element = WebDriverWait(bot, timeout).until(
            EC.presence_of_element_located((by, value))
        )
        if message:
            logging.info(message)
        return element
    except TimeoutException:
        logging.error(f"⚠️ Timeout waiting for element: {value}")
        return None

def click_with_retry(element, max_attempts=3):
    """Helper function to retry clicking with multiple attempts"""
    for attempt in range(max_attempts):
        try:
            element.click()
            return True
        except ElementClickInterceptedException:
            if attempt == max_attempts - 1:
                raise
            time.sleep(1)
    return False

def post_to_facebook(bot, video_url):
    """Post video link to Facebook page using exact selectors"""
    try:
        # Navigate to the Facebook page
        bot.get("https://www.facebook.com/oddityworldtubee/")
        logging.info("🌐 Opening Facebook page...")
        
        # Wait for page load and scroll slightly
        time.sleep(5)
        bot.execute_script("window.scrollBy(0, 100);")
        
        # Find "Create Post" area using the specific class
        create_post_button = wait_and_find_element(
            bot,
            By.CSS_SELECTOR,
            'div[class*="x1i10hfl"][class*="x1n2onr6"][class*="xt7dq6l"][role="button"]',
            timeout=10,
            message="Found create post button"
        )
        
        if create_post_button:
            click_with_retry(create_post_button)
            time.sleep(3)
        
        # Find post box using exact class and attributes
        post_box = wait_and_find_element(
            bot,
            By.CSS_SELECTOR,
            'div.xzsf02u.x1a2a7pz.x1n2onr6.x14wi4xw.x9f619.x1lliihq.x5yr21d.xh8yej3[contenteditable="true"][role="textbox"]',
            timeout=10,
            message="Found post box"
        )
        
        if not post_box:
            # Try alternative selector
            post_box = wait_and_find_element(
                bot,
                By.CSS_SELECTOR,
                'div[aria-label="بم تفكر؟"][role="textbox"]',
                timeout=10
            )
        
        if not post_box:
            raise Exception("Could not find post box")
        
        # Click and enter text
        click_with_retry(post_box)
        time.sleep(1)
        
        # Enter text without emoji to avoid encoding issues
        post_text = f"New video uploaded: {video_url}"
        for char in post_text:
            post_box.send_keys(char)
            time.sleep(0.1)
        
        logging.info("📝 Entered post text.")
        time.sleep(2)
        
        # Find publish button using exact class
        publish_button = wait_and_find_element(
            bot,
            By.CSS_SELECTOR,
            'div.x1i10hfl.xjbqb8w.x1ejq31n.xd10rxx.x1sy0etr.x17r0tee.x972fbf.xcfux6l.x1qhh985.xm0m39n.xe8uvvx.xdj266r.x11i5rnm.xat24cr.x1mh8g0r.xexx8yu.x4uap5.x18d9i69.xkhd6sd.x16tdsg8.x1hl2dhg.xggy1nq.x1h6gzvc.x1o1ewxj.x3x9cwd.x1e5q0jg.x13rtm0m.x87ps6o.x1lku1pv.x1a2a7pz.x9f619.x3nfvp2.xdt5ytf.xl56j7k.x1n2onr6.xh8yej3[role="button"][aria-label="نشر"]',
            timeout=10
        )
        
        if not publish_button:
            # Try alternative selector
            publish_button = wait_and_find_element(
                bot,
                By.CSS_SELECTOR,
                'div[aria-label="نشر"][role="button"]',
                timeout=10
            )
        
        if not publish_button:
            raise Exception("Could not find publish button")
        
        # Click publish and wait
        click_with_retry(publish_button)
        logging.info("✅ Clicked publish button")
        time.sleep(10)
        
        return True

    except Exception as e:
        logging.error(f"⚠️ Failed to post to Facebook: {str(e)}")
        return False

def setup_browser():
    """Initialize Chrome browser with improved options"""
    options = webdriver.ChromeOptions()
    options.binary_location = CANARY_BINARY_PATH
    options.add_argument(f"--user-data-dir={USER_DATA_DIR}")
    options.add_argument("--profile-directory=Default")
    options.add_argument("--start-maximized")
    options.add_argument("--disable-notifications")
    options.add_argument("--disable-gpu")
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-dev-shm-usage")
    options.add_argument('--lang=en-US')
    options.add_argument('--disable-extensions')
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option("useAutomationExtension", False)
    options.add_argument('--force-device-scale-factor=1')

    service = Service(executable_path=CHROMEDRIVER_PATH)
    return webdriver.Chrome(service=service, options=options)

if __name__ == "__main__":
    video_url = "https://youtu.be/GXlWI4UCEPM"
    bot = None
    
    try:
        bot = setup_browser()
        success = post_to_facebook(bot, video_url)
        if success:
            logging.info("🎉 Successfully posted the link!")
        else:
            logging.error("❌ Failed to post the link.")
    except Exception as e:
        logging.error(f"⚠️ Unexpected error: {str(e)}")
    finally:
        if bot:
            bot.quit() بص استخرج الفكرة فقط والمسارات واعد بناء كود كامل كليا