from selenium import webdriver
from selenium.webdriver.firefox.service import Service
from selenium.webdriver.firefox.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


def load_url(
    url: str,
    file_name: str = "temp.html",
    gecko_driver_path: str = None,
    headless: bool = True,
):
    """
    Loads a webpage using Firefox (Selenium) and saves the fully rendered HTML.

    Args:
        url (str): URL to fetch.
        file_name (str): Output HTML file name.
        gecko_driver_path (str): Path to GeckoDriver. If None, tries system PATH.
        headless (bool): Run browser in headless mode.
    """

    # Configure Firefox options
    firefox_options = Options()
    if headless:
        firefox_options.add_argument("--headless")
    firefox_options.add_argument("--disable-gpu")

    try:
        # If no path is provided, use PATH-installed geckodriver
        service = Service(gecko_driver_path) if gecko_driver_path else Service()

        driver = webdriver.Firefox(service=service, options=firefox_options)

        driver.get(url)

        WebDriverWait(driver, 20).until(
            EC.presence_of_element_located((By.ID, "root"))
        )

        WebDriverWait(driver, 20).until(
            EC.presence_of_element_located((By.CLASS_NAME, "post-card__header"))
        )

        # Save the full page content
        content = driver.page_source
        with open(file_name, "w", encoding="utf-8") as f:
            f.write(content)

    finally:
        driver.quit()