"""
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 random
import time
from abrasio import Abrasio, FingerprintConfig, AbrasioConfig
from abrasio.utils import human_scroll, human_wait, simulate_reading, human_click, human_type, human_move_to


async def _strip_coep(route):
    """
    Remove Cross-Origin-Embedder-Policy e Cross-Origin-Opener-Policy das respostas
    do site alvo. Sem isso o browser bloqueia o iframe do reCAPTCHA Enterprise
    (google.com não envia Cross-Origin-Resource-Policy, violando o COEP do site).
    """
    try:
        response = await route.fetch()
        headers = {
            k: v for k, v in response.headers.items()
            if k.lower() not in (
                "cross-origin-embedder-policy",
                "cross-origin-opener-policy",
            )
        }
        await route.fulfill(
            status=response.status,
            headers=headers,
            body=await response.body(),
        )
    except Exception:
        await route.continue_()


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,
        humanize=True,
    ) 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://2captcha.com/demo/recaptcha-v3-enterprise")
        await human_wait(5, 10)
        await human_click(page, '//*[@id="root"]/div[2]/main/div/div/div[1]/section/div/form/div[2]/button[1]')
        await human_wait(5, 10)
        await page.screenshot(path="2captcha.png", full_page=True)
        print("Fingerprint.com test saved to 2captcha.png")
        await page.route("https://cdwfazenda.paas.pr.gov.br/**", _strip_coep)
        await page.goto("https://cdwfazenda.paas.pr.gov.br/cdwportal/certidao/automatica", wait_until="domcontentloaded")
        await human_wait(5,7)  # Wait for login page to load
        #await page.screenshot(path="loginpage.png", full_page=True)
        print("Login page screenshot saved to loginpage.png")
        #await human_click(page, '//*[@id="app"]/div/header/div/button[1]')
        #await human_click(page, 'a.q-item.q-item-type.row.no-wrap.q-item--dense.q-router-link--exact-active.q-router-link--active.q-item--clickable.q-link.cursor-pointer.q-focusable.q-hoverable.app-subitem')
        await page.screenshot(path="home.png", full_page=True)
        await simulate_reading(page, 2, 5)

        await page.wait_for_selector('//*[@id="app"]/div/div[3]/main/form/label/div')
        #await page.locator("#accountId").click()
        #cpf = input("Enter the CPF: ")
        await human_type(page, "03360387000185", '//*[@id="app"]/div/div[3]/main/form/label/div')
        #await page.keyboard.type"48500067870", delay=100)
        for i in range(random.randint(1, 3)):
            await human_wait(1, 2)
            await human_move_to(page, random.randint(100, 500), random.randint(100, 500))
        await human_move_to(page, random.randint(100, 500), random.randint(100, 500))
        #await human_wait(8,10)
        await simulate_reading(page, 2, 5)
        #await human_scroll(page, 400, 500)
        await human_click(page, "#app > div > div.q-page-container.app-page-container > main > form > div > button > span.q-btn__content.text-center.col.items-center.q-anchor--skip.justify-center.row > span")
        #await page.screenshot(path="login.png", full_page=True)
        await page.screenshot(path="certidao.png", full_page=True)
        await human_click(page, '//*[@id="q-portal--dialog--1"]/div/div[2]/div/div[3]/button[2]')
        await page.screenshot(path="solicitado.png", full_page=True)
        
        print("Sucesso")




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