import os
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):
    browser = playwright.chromium.launch(
        headless=True, 
        args=["--disable-blink-features=AutomationControlled"]
    )
    
    # 🛑 THE FIX: Dynamically build the absolute path to state.json
    script_dir = os.path.dirname(os.path.abspath(__file__))
    state_file_path = os.path.join(script_dir, "state.json")
    
    try:
        print(f"Attempting to load session from: {state_file_path}")
        context = browser.new_context(
            storage_state=state_file_path,
            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 as e:
        print(f"Failed to load {state_file_path}: {e}")
        print("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
        
        print("Waiting for fee calculation and for the Continue button to unlock...")
        page.wait_for_timeout(3000) # Give Angular a moment to register the dropdown change
        
        # Smart Wait: Pause the script until the button specifically loses its 'disabled' state
        try:
            page.wait_for_function("document.querySelector('#parent_id button').disabled === false", timeout=10000)
        except Exception:
            print("Warning: Continue button never unlocked. Attempting to force click anyway...")

        page.screenshot(path="1_before_submit.png", full_page=True)

        print("Submitting initial reservation...")
        page.evaluate("document.querySelector('#parent_id button').click()")
        
        # ==========================================
        # 🛑 DYNAMIC PAYMENT FLOW CHECK (STRICT MODE)
        # ==========================================
        print("Waiting for portal to load the payment screen (up to 20 seconds)...")
        
        try:
            # 1. Check if the payment button appears
            pay_btn = page.locator("button#submit")
            pay_btn.wait_for(state="visible", timeout=20000)
            payment_screen_found = True
            print("Payment screen loaded!")
        except Exception:
            payment_screen_found = False
            print("No payment screen detected after 20s. Assuming short booking flow...")

        # 2. If it IS a payment day, strictly enforce the payment flow
        if payment_screen_found:
            print("Waiting for Stripe to load the saved card...")
            page.wait_for_timeout(3000)
            
            # ==========================================
            # 🛑 NEW: WAKE UP STRIPE
            # ==========================================
            print("Clicking the saved card area to trigger Stripe's ready event...")
            try:
                # Click the wrapper that holds the Stripe iframe to force interaction
                page.locator('#payment-element').click(force=True)
                page.wait_for_timeout(1000)
                
                # Fallback: Try clicking the 'See more' text if it's reachable outside the iframe
                if page.get_by_text("See more").is_visible():
                    page.get_by_text("See more").click(force=True)
                    page.wait_for_timeout(1000)
            except Exception as e:
                print("Note: Could not click card area, continuing...")
            # ==========================================

            print("Waiting for the 'Pay and reserve' button to unlock...")
            
            # Wait up to 15 seconds for the button to lose its 'disabled' state
            try:
                page.wait_for_function(
                    "document.querySelector('button#submit') && document.querySelector('button#submit').disabled === false", 
                    timeout=15000
                )
            except Exception:
                print("Warning: Stripe took too long or button stayed locked.")
                
            print("Clicking final 'Pay and reserve' button...")
            page.evaluate("document.querySelector('button#submit').click()")
            
            print("Waiting for payment to process and confirm...")
            # 🛑 STRICT CHECK: If the payment works, the screen MUST change (the button disappears)
            try:
                pay_btn.wait_for(state="hidden", timeout=15000)
                print("Payment successful! Confirmation screen reached.")
            except Exception:
                # If the button is still on screen 15 seconds after clicking, IT FAILED.
                page.screenshot(path="error_payment_stuck.png", full_page=True)
                raise Exception("Payment button was clicked, but the transaction did not go through.")

        # Give the final confirmation page a moment to render before taking the screenshot
        page.wait_for_timeout(3000)
        # ==========================================
        
        # 📸 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)