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')

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

        # Check if we were redirected to Microsoft login (meaning token expired)
        if "login.microsoftonline.com" in page.url:
            print("Session expired! Capturing debug files...")
            page.screenshot(path="error_token_expired.png", full_page=True)
            with open("error_token_expired_source.html", "w", encoding="utf-8") as file:
                file.write(page.content())
                
            send_ifttt_webhook(event2, "Erro de autenticacao - Token Expirado")
            browser.close()
            return

        # Wait for the ServiceNow "Loading..." spinner to disappear
        print("Waiting for ServiceNow portal to render...")
        try:
            page.wait_for_selector('.sp-page-loader', state='hidden', timeout=15000)
        except Exception:
            pass
            
        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

        # Select the parking location
        print("No existing reservation found. Selecting NY1350...")
        page.select_option('select[name="locs"]', label='NY1350')
        page.screenshot(path="1_before_submit.png", full_page=True)

        # Click the initial continue/book button
        print("Submitting initial reservation...")
        page.evaluate("document.querySelector('#parent_id button').click()")
        
        # ==========================================
        # 🛑 DYNAMIC FLOW DETECTION
        # ==========================================
        print("Checking if extra payment steps are required...")
        
        try:
            # Look for the Payment button
            payment_btn = page.locator("button:has-text('Payment')")
            payment_btn.wait_for(state="visible", timeout=5000)
            
            print("Payment screen detected! Executing extra steps...")
            raise Exception("Payment flow detected") # Force jump to payment handling
            #payment_btn.click(force=True)
            
            # Wait a moment for the click to register and next screen to appear
            page.wait_for_timeout(2000)
            
            # 🛑 OPTIONAL FINAL SUBMIT CHECK
            print("Checking if Final Submit screen appeared...")
            try:
                final_submit_btn = page.locator("button:has-text('Submit')")
                final_submit_btn.wait_for(state="visible", timeout=5000)
                print("Final Submit button found! Clicking...")
                final_submit_btn.click(force=True)
                page.wait_for_timeout(4000) # Wait for final processing
            except Exception:
                print("No Final Submit screen required. Proceeding...")
            
        except Exception:
            # If the timeout expires, it means the Payment button never showed up.
            print("No payment screen detected. Assuming short booking flow...")
            page.wait_for_timeout(3000) # Give the short flow a few seconds to finish processing

        # ==========================================
        
        # 📸 Debugging: Take a screenshot AFTER everything is done
        page.screenshot(path="2_after_submit.png", full_page=True)
        
        print("Reservation completed 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)