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...")
        # Navigate and wait only for the basic page to load, not the background scripts
        page.goto('https://iadb.service-now.com/sp?id=parking_pass_screen', wait_until='domcontentloaded')

        # Give Microsoft SSO exactly 5 seconds to finish bouncing, regardless of network state
        page.wait_for_timeout(5000)

        # 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

        # ==========================================
        # 🛑 LOCATION SELECTION WITH FAILOVER
        # ==========================================
        print("No existing reservation found. Checking availability for NY1350...")
        location_selected = False
        
        # 1st Attempt: Primary Location (NY1350)
        try:
            page.select_option('select[name="locs"]', label='NY1350', timeout=10000)
            print("Successfully selected NY1350.")
            location_selected = True
        except Exception as e:
            if "Timeout" in str(e):
                print("NY1350 is full or unavailable. Attempting backup location (NY1300)...")
            else:
                raise e # If it's a completely different error, crash and log it

        # 2nd Attempt: Backup Location (NY1300) - Only runs if NY1350 failed
        if not location_selected:
            try:
                page.select_option('select[name="locs"]', label='NY1300', timeout=10000)
                print("Successfully selected NY1300.")
                location_selected = True
            except Exception as e:
                if "Timeout" in str(e):
                    print("Both NY1350 and NY1300 are fully booked. Aborting.")
                    page.screenshot(path="error_all_sold_out.png", full_page=True)
                    send_ifttt_webhook(event, "Estacionamentos Lotados (NY1350 e NY1300)")
                    return # Exits the script entirely
                else:
                    raise e
        
        # If we reach this line, one of the locations was successfully selected!
        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  showed up.
            print("No payment screen detected. Assuming short booking ...")
        
        # 📸 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)