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
        # ==========================================
        print("Waiting for portal to load the payment screen (up to 20 seconds)...")
        
        try:
            # Look for the exact ID of the final payment button rather than relying on text
            pay_btn = page.locator("button#submit")
            pay_btn.wait_for(state="visible", timeout=20000)
            
            print("Payment screen loaded! Giving Stripe 3 seconds to authenticate saved card...")
            # This is critical: Wait 3 seconds for the Saved Visa card widget to finish loading
            page.wait_for_timeout(3000)
            
            print("Clicking final reserve button...")
            pay_btn.click(force=True)
            
            # Give the final transaction time to process
            page.wait_for_timeout(6000)
            
        except Exception:
            print("No payment screen detected after 20s. Assuming short booking flow...")
            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)