from playwright.sync_api import sync_playwright
import requests

# IFTTT Config
event = 'tbn_event'
event2 = 'Authentication_Failed'
key = 'dreYWZN6BkiImePegTZ5et' # Replace with your actual key

def send_ifttt_webhook(event_name, message):
    url = f'https://maker.ifttt.com/trigger/{event_name}/with/key/{key}'
    requests.post(url, json={'value1': message})
    print(f"Webhook sent: {message}")

def run(playwright):
    # 1. Launch with the AutomationControlled bypass flag for Microsoft
    browser = playwright.chromium.launch(
        headless=True, 
        args=["--disable-blink-features=AutomationControlled"]
    )
    
    # LOAD THE SAVED SESSION STATE & MIMIC A REAL WINDOWS LAPTOP
    try:
        context = browser.new_context(
            storage_state="state.json",
            user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
            viewport={"width": 1920, "height": 1080}
        )
    except Exception:
        print("state.json not found! Please run setup_auth.py first.")
        send_ifttt_webhook(event2, "state.json missing. Reautenticando.")
        return

    page = context.new_page()

    try:
        print("Navigating to parking portal...")
        page.goto('https://iadb.service-now.com/sp?id=parking_pass_screen')

        # 🛑 FIX 1: Wait for any silent Microsoft SSO "bounces" to finish
        page.wait_for_load_state('networkidle')

        # NOW check the URL after the dust has settled
        if "login.microsoftonline.com" in page.url:
            print("Session expired! Capturing debug files...")
            
            # 📸 Debugging: Take a screenshot of the Microsoft page
            page.screenshot(path="error_token_expired.png", full_page=True)
            
            # 📄 Debugging: Dump the page source
            with open("error_token_expired_source.html", "w", encoding="utf-8") as file:
                file.write(page.content())
                
            # Using event2 for Authentication Failed
            send_ifttt_webhook(event2, "Erro de autenticacao - Token Expirado")
            browser.close()
            return

        # 🛑 FIX 2: Wait for the ServiceNow "Loading..." spinner to disappear
        print("Waiting for ServiceNow portal to render...")
        try:
            # Explicitly wait for the exact spinner class from your HTML dump to be hidden
            page.wait_for_selector('.sp-page-loader', state='hidden', timeout=15000)
        except Exception:
            pass # If the spinner is already gone, just continue
            
        # Give the "Already booked" modal animation a moment to trigger
        page.wait_for_timeout(2000) 

        # 🛑 CHECK FOR MODAL
        if page.get_by_text("You already have a Parking Pass for today.").is_visible() or \
           page.get_by_text("Show me my Parking Pass").is_visible():
            
            print("Detected existing reservation modal. Aborting booking.")
            send_ifttt_webhook(event, "Parking scheduled already")
            page.screenshot(path="already_booked.png", full_page=True)
            return

        # If no modal, proceed with selecting the parking location
        print("No existing reservation found. Selecting NY1350...")
        page.select_option('select[name="locs"]', label='NY1350')

        # 📸 Debugging: Take a screenshot BEFORE clicking submit
        page.screenshot(path="1_before_submit.png", full_page=True)

        # Click the continue/book button using JS to bypass actionability checks
        print("Submitting reservation...")
        page.evaluate("document.getElementById('parent_id').click()")
        
        # Force the script to wait 5 seconds before checking the result
        page.wait_for_timeout(5000) 
        
        # 📸 Debugging: Take a screenshot AFTER clicking submit
        page.screenshot(path="2_after_submit.png", full_page=True)
        
        print("Reservation submitted successfully!")
        send_ifttt_webhook(event, "Sucesso no agendamento")

    except Exception as e:
        print(f"An error occurred: {e}")
        send_ifttt_webhook(event, "Falha Geral no Agendamento")

    finally:
        browser.close()

if __name__ == "__main__":
    with sync_playwright() as playwright:
        run(playwright)
