"""
Basic example using Abrasio in cloud (paid) mode.

This example demonstrates how to use Abrasio with the cloud browser
service using an API key.

Before running:
    pip install abrasiohttps://nopecha.com/setup#sub_1T4CnfCRwBwvt6ptJ7ibOS5S
    export ABRASIO_API_KEY=sk_live_xxx
"""

import asyncio
import os
import time
from abrasio import Abrasio, FingerprintConfig, AbrasioConfig
from abrasio.utils import human_scroll, human_wait, simulate_reading, human_click, human_type


async def main():
    # Get API key from environment
    api_key = "sk_live_v9mZmBNvZHwblE7-hOwCQ3xgyFE7oeo0kTSu8Nt6p34"#"sk_live_AUEnBxlYgqcm4Cc6smA814Vzk067r6bSiIV7cunCkVA"#"sk_live_Qct3WeYuLhXRxPJdLpP2X8X0YqCwUyLUhPywXwmBsyk"#os.getenv("ABRASIO_API_KEY")
    if not api_key:
        print("Set ABRASIO_API_KEY environment variable to use cloud mode")
        print("Example: export ABRASIO_API_KEY=sk_live_xxx")
        return
    config:AbrasioConfig = FingerprintConfig(
        webgl=True,
        webrtc=True,
        )
    # Cloud mode - with API key and region
    # For local testing use: api_url="http://localhost:8000"
    async with Abrasio(
        api_key ="sk_live_J3x6He9d35C1tCSt2mmuOtcNIFk_rVtwWdU-R_donSo",
        region="br",
        proxy={"server": "http://network.joinmassive.com:65534", "username": "mpuW15al5h-country-BR-subdivision-SP", "password": "moS1BoA2RbKFIwu9BUr0"},
        #api_key=api_key,
        # api_url="http://localhost:8000",  # Uncomment for local testing
        #region="BR",
        #config=config,
        device="mobile",
        url="https://www.gov.br",
        profile_id="355161aee2a8",
        #proxy={"server": "gw-open.netnut.net:5959", "username": "Scrapetech-res-br", "password": "Wg0d5619HrBLesl"},
        #proxy=f'http://Scrapetech-res-us:Wg0d5619HrBLesl@gw-open.netnut.net:5959'
          # Disable WebGL and Canvas for testing
        #headless=True,
        #device="mobile",
        headless=False,
        
    ) as browser:
        page = await browser.new_page()
        # Live view URL (if enabled on server)
        if browser.live_view_url:
            print(f"Watch live: {browser.live_view_url}")
        
        await page.goto("https://cidadao.mg.gov.br/#/login", wait_until="domcontentloaded")
        await human_wait(5,7)  # Wait for login page to load
        #await page.locator("//*[contains(text(), 'Aceitar')]").click()
        #await page.screenshot(path="loginpage.png", full_page=True)
        print("Login page screenshot saved to loginpage.png")
        await page.locator(".govBrBtn").is_visible()
        await page.locator(".govBrBtn").click()

        await page.wait_for_selector("#accountId")
        #await page.locator("#accountId").click()
        #cpf = input("Enter the CPF: ")
        await human_type(page, "48500067870", "#accountId")
        #await page.keyboard.type"48500067870", delay=100)

        await page.locator('#enter-account-id').click()
        #await page.screenshot(path="login.png", full_page=True)
        await human_wait(20,40)
        await page.locator("#password").is_visible()
        #await page.screenshot(path="senha.png", full_page=True)
        await page.locator("#password").click()
        #senha = input("Enter the password: ")
        await page.keyboard.type("Ovalle#442", delay=100)

        await page.locator('#submit-button').click()
       
        await page.wait_for_selector(".gdd-close-btn")
        await page.locator(".gdd-close-btn").click()
        await page.locator("#otpInput").is_visible()
        await page.screenshot(path="otp.png", full_page=True)
        await page.locator("#otpInput").click()
        codigo = input("Enter the OTP code: ")
        await page.keyboard.type(codigo, delay=100)
        await page.mouse.move(5,5)
        await page.locator("#enter-offline-2fa-code").click()
        cookies = await page.context.cookies()  

        await page.wait_for_selector(".main-menu")
        await page.locator(".main-menu").click()

        await page.wait_for_selector("//*[contains(text(), 'Veículos e Condutores (Trânsito)')]")
        await page.locator("//*[contains(text(), 'Veículos e Condutores (Trânsito)')]").click()
        await human_wait(2,3)
        await human_click(page, 'body > app-root > app-cookie-consent-banner > div > div > div.cookie-buttons > p-button:nth-child(2) > button')
        await page.screenshot(path="menu.png", full_page=True)
        await page.wait_for_selector('//*[@id="outlet"]/app-servicos/div/div/div[4]/div[1]/button')
        await page.locator('//*[@id="outlet"]/app-servicos/div/div/div[4]/div[1]/button').click()
        await page.get_by_text("Situação do Veículo").scroll_into_view_if_needed()
        #await human_scroll(page, 900, 1300)
        await human_click(page, "//*[contains(text(), 'Situação do Veículo')]")

        await human_wait(4,10)
        await simulate_reading(page, 2, 8)
        await human_click(page, "#placa")
        await human_type(page, "RVX1D55", "#placa")
        await human_type(page, "9BWAG45U6PT098548", "#chassi")

        async with page.expect_response(
            lambda r: "mgapp.mg.gov.br/egov-servicos-web/rest/veiculos/situacao" in r.url
        ) as response_info:
            await human_click(page, "//*[contains(text(), 'Pesquisar')]")

        #response = await response_info.value
        #veiculo_json = await response.json()
        await human_wait(5,10)
        await page.screenshot(path="situacao.png", full_page=True)
        #print(veiculo_json)
        print(cookies)
        print("Sucesso")




if __name__ == "__main__":
    asyncio.run(main())
