#Auth_Test_for_Parking
import os
import requests
from playwright.sync_api import sync_playwright

username = "abona@iadb.org"

def disparar_webhook_ifttt(mensagem):
    """Envia a notificação via Webhook do IFTTT."""
    ifttt_key = os.environ.get("IFTTT_KEY")
    if not ifttt_key:
        print("⚠️ ERRO: Chave IFTTT_KEY não encontrada nas variáveis de ambiente.")
        return

    # Substitua pelo nome do evento configurado no seu IFTTT
    evento = "tbn_event" 
    url = f"https://maker.ifttt.com/trigger/{evento}/with/key/{ifttt_key}"
    
    payload = {"value1": mensagem}
    
    try:
        response = requests.post(url, json=payload)
        if response.status_code == 200:
            print(f"✅ Webhook enviado com sucesso: '{mensagem}'")
        else:
            print(f"⚠️ Falha ao enviar webhook. Status: {response.status_code}")
    except Exception as e:
        print(f"⚠️ Erro na requisição do webhook: {e}")

def run(playwright):
    browser = playwright.chromium.launch(
        headless=True, 
        args=["--disable-blink-features=AutomationControlled"]
    )

    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"

    script_dir = os.path.dirname(os.path.abspath(__file__))
    state_file_path = os.path.join(script_dir, "state.json")

    if os.path.exists(state_file_path):
        print(f"Arquivo state.json encontrado. Testando a sessão...")
        try:
            test_context = browser.new_context(
                storage_state=state_file_path,
                user_agent=user_agent,
                viewport={"width": 1920, "height": 1080}
            )
            test_page = test_context.new_page()
            
            test_page.goto('https://iadb.service-now.com/sp?id=parking_pass_screen', wait_until='domcontentloaded')
            test_page.wait_for_timeout(5000)
            
            if "login.microsoftonline.com" not in test_page.url:
                print("✅ Sessão válida.")
                disparar_webhook_ifttt("o login ainda é valido")
            else:
                print("⚠️ Sessão expirada.")
                disparar_webhook_ifttt("atualizar o login apenas")
                
            test_context.close()
            
        except Exception as e:
            print(f"⚠️ Erro ao testar o state.json: {e}")
            disparar_webhook_ifttt("atualizar o login apenas")
    else:
        print(f"Arquivo de estado não encontrado em {state_file_path}.")
        disparar_webhook_ifttt("atualizar o login apenas")

    browser.close()

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