# run_local_selenium.py
import http.server, socketserver, threading, os, sys, time
from pathlib import Path

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager

PORT = 5500

def start_server(base_dir: Path, port: int):
    os.chdir(base_dir)
    handler = http.server.SimpleHTTPRequestHandler
    httpd = socketserver.TCPServer(("127.0.0.1", port), handler)
    threading.Thread(target=httpd.serve_forever, daemon=True).start()
    return httpd

def resolve_html_path():
    # 1) if filename is provided, use it relative to CWD
    if len(sys.argv) > 1:
        p = Path.cwd() / sys.argv[1]
        if p.exists():
            return p
        else:
            raise FileNotFoundError(f"Not found: {p}")
    # 2) fallback: try htmlm.html in CWD
    p = Path.cwd() / "htmlm.html"
    if p.exists(): return p
    # 3) last resort: pick the first .html in CWD
    htmls = list(Path.cwd().glob("*.html"))
    if htmls:
        print(f"[info] No name provided; using {htmls[0].name}")
        return htmls[0]
    raise FileNotFoundError("No .html file found in current folder.")

def main():
    html_path = resolve_html_path()
    httpd = start_server(html_path.parent, PORT)
    url = f"http://127.0.0.1:{PORT}/{html_path.name}"
    print(f"Serving {html_path.name} -> {url}")

    opts = Options()
    opts.add_argument("--start-maximized")
    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=opts)

    try:
        driver.get(url)
        wait = WebDriverWait(driver, 15)

        # Select 2nd offer if present
        offers = wait.until(EC.presence_of_all_elements_located(
            (By.CSS_SELECTOR, "._rsi-quantity-offers-offer-container")))
        if len(offers) >= 2:
            offers[1].click()
            time.sleep(0.4)

        # Fill fields (adjust as needed)
        def fill(css, val):
            el = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, css)))
            el.clear(); el.send_keys(val)
        fill("#_rsi-field-first_name", "Mohamed Ali")
        fill("#_rsi-field-phone", "0612345678")
        fill("#_rsi-field-city", "Casablanca, Maarif")

        # Click confirm
        btn = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button._rsi-modal-submit-button")))
        btn.click()
        print("Clicked confirm.")
        time.sleep(5000)
    finally:
        time.sleep(5000)
        driver.quit(); httpd.shutdown()
        print("Done.")

if __name__ == "__main__":
    main()
