import asyncio
from playwright.async_api import async_playwright
import requests
import random
import re
import threading
import time
import os
import tempfile
import shutil
import json
from datetime import datetime
from faker import Faker
import math

fake = Faker('pt_BR')

from config import SMS_ACTIVATE_API_KEY, AMAZON_SERVICE_CODE, BRAZIL_COUNTRY_CODE

numero_lock = asyncio.Lock()

QUANTUM_FINGERPRINT_2026 = """


(function() {
    'use strict';
    
    const sessionId = Date.now() + Math.random();
    
    // === CAMADA 1: NAVIGATOR OVERRIDE ===
    const originalNavigator = window.navigator;
    
    Object.defineProperty(window, 'navigator', {
        value: new Proxy(originalNavigator, {
            get(target, prop) {
                // Propriedades críticas
                switch(prop) {
                    case 'webdriver':
                        return undefined;
                    case 'plugins':
                        return {
                            length: 3,
                            item: function(index) {
                                const plugins = [
                                    { name: 'Chrome PDF Viewer', filename: 'internal-pdf-viewer' },
                                    { name: 'Chrome PDF Plugin', filename: 'mhjfbmdgcfjbbpaeojofohoefgiehjai' },
                                    { name: 'Native Client', filename: 'internal-nacl-plugin' }
                                ];
                                return plugins[index] || null;
                            },
                            [Symbol.iterator]: function*() {
                                yield { name: 'Chrome PDF Viewer', filename: 'internal-pdf-viewer' };
                                yield { name: 'Chrome PDF Plugin', filename: 'mhjfbmdgcfjbbpaeojofohoefgiehjai' };
                                yield { name: 'Native Client', filename: 'internal-nacl-plugin' };
                            }
                        };
                    case 'languages':
                        return ['pt-BR', 'pt', 'en-US', 'en'];
                    case 'language':
                        return 'pt-BR';
                    case 'platform':
                        return 'Win32';
                    case 'deviceMemory':
                        return 8;
                    case 'hardwareConcurrency':
                        return 4;
                    case 'maxTouchPoints':
                        return 0;
                    case 'userAgentData':
                        return {
                            brands: [
                                { brand: 'Chromium', version: '131' },
                                { brand: 'Google Chrome', version: '131' },
                                { brand: 'Not;A=Brand', version: '99' }
                            ],
                            mobile: false,
                            platform: 'Windows',
                            getHighEntropyValues: () => Promise.resolve({
                                architecture: 'x86',
                                bitness: '64',
                                brands: [
                                    { brand: 'Chromium', version: '131' },
                                    { brand: 'Google Chrome', version: '131' },
                                    { brand: 'Not;A=Brand', version: '99' }
                                ],
                                mobile: false,
                                platform: 'Windows',
                                platformVersion: '10.0.0'
                            })
                        };
                    default:
                        return target[prop];
                }
            }
        }),
        writable: false,
        configurable: false
    });
    
    // === CAMADA 2: CHROME OBJECT CLEANUP ===
    window.chrome = {
        runtime: {},
        app: {
            isInstalled: false,
            InstallState: 'DISABLED',
            RunningState: 'RUNNING'
        },
        webstore: {},
        csi: function() {},
        loadTimes: function() {
            return {
                requestTime: 0,
                startLoadTime: 0,
                finishDocumentLoadTime: 0,
                finishLoadTime: 0,
                navigationType: 'Reload',
                wasFetchedViaSpdy: false,
                wasNpnNegotiated: true,
                npnNegotiatedProtocol: 'h2'
            };
        }
    };
    
    // === CAMADA 3: CANVAS FINGERPRINT PROTECTION ===
    const canvasNoiseCache = new Map();
    
    function generateCanvasNoise(width, height) {
        const key = `${width}x${height}`;
        if (canvasNoiseCache.has(key)) {
            return canvasNoiseCache.get(key);
        }
        
        const canvas = document.createElement('canvas');
        canvas.width = width;
        canvas.height = height;
        const ctx = canvas.getContext('2d');
        
        // Gradiente base
        const gradient = ctx.createLinearGradient(0, 0, width, height);
        const hue = sessionId % 360;
        gradient.addColorStop(0, `hsl(${hue}, 70%, 60%)`);
        gradient.addColorStop(0.5, `hsl(${(hue + 60) % 360}, 80%, 50%)`);
        gradient.addColorStop(1, `hsl(${(hue + 120) % 360}, 60%, 70%)`);
        
        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, width, height);
        
        // Adiciona texto com sombra
        ctx.shadowColor = 'rgba(0,0,0,0.3)';
        ctx.shadowBlur = 3;
        ctx.shadowOffsetX = 1;
        ctx.shadowOffsetY = 1;
        
        ctx.fillStyle = '#FFFFFF';
        ctx.font = '18px Arial';
        ctx.fillText('Quantum Cloak 2026', 20, 50);
        
        // Remove sombra
        ctx.shadowColor = 'transparent';
        ctx.shadowBlur = 0;
        ctx.shadowOffsetX = 0;
        ctx.shadowOffsetY = 0;
        
        // Adiciona ruído procedural
        const imageData = ctx.getImageData(0, 0, width, height);
        const data = imageData.data;
        
        for (let i = 0; i < data.length; i += 4) {
            const x = (i / 4) % width;
            const y = Math.floor((i / 4) / width);
            
            // Ruído baseado em função senoidal
            const noise = Math.sin(x * 0.01 + sessionId) * Math.cos(y * 0.01 + sessionId) * 20;
            const microNoise = Math.sin(sessionId * x * y * 0.00001) * 2;
            
            data[i] = Math.min(255, Math.max(0, data[i] + noise + microNoise));
            data[i + 1] = Math.min(255, Math.max(0, data[i + 1] + noise * 0.8 + microNoise));
            data[i + 2] = Math.min(255, Math.max(0, data[i + 2] + noise * 0.6 + microNoise));
        }
        
        ctx.putImageData(imageData, 0, 0);
        
        // Adiciona formas geométricas
        ctx.strokeStyle = 'rgba(255, 255, 255, 0.2)';
        ctx.lineWidth = 1;
        
        for (let i = 0; i < 3; i++) {
            ctx.beginPath();
            const radius = 15 + i * 10;
            const centerX = width * 0.5 + Math.cos(i * 1.2) * 40;
            const centerY = height * 0.5 + Math.sin(i * 1.2) * 40;
            
            ctx.arc(centerX, centerY, radius, 0, Math.PI * 2);
            ctx.stroke();
        }
        
        canvasNoiseCache.set(key, canvas);
        return canvas;
    }
    
    const originalToDataURL = HTMLCanvasElement.prototype.toDataURL;
    const originalToBlob = HTMLCanvasElement.prototype.toBlob;
    
    HTMLCanvasElement.prototype.toDataURL = function(type, quality) {
        if (this.width > 10 && this.height > 10) {
            const canvas = generateCanvasNoise(this.width, this.height);
            return canvas.toDataURL(type, quality);
        }
        return originalToDataURL.call(this, type, quality);
    };
    
    HTMLCanvasElement.prototype.toBlob = function(callback, type, quality) {
        if (this.width > 10 && this.height > 10) {
            const canvas = generateCanvasNoise(this.width, this.height);
            canvas.toBlob(callback, type, quality);
            return;
        }
        originalToBlob.call(this, callback, type, quality);
    };
    
    // === CAMADA 4: WEBGL PROTECTION ===
    const originalGetContext = HTMLCanvasElement.prototype.getContext;
    
    HTMLCanvasElement.prototype.getContext = function(contextType, contextAttributes) {
        const context = originalGetContext.call(this, contextType, contextAttributes);
        
        if (contextType === 'webgl' || contextType === 'webgl2') {
            const originalGetParameter = context.getParameter;
            
            context.getParameter = function(pname) {
                switch(pname) {
                    case 37445: // UNMASKED_VENDOR_WEBGL
                        return 'NVIDIA Corporation';
                    case 37446: // UNMASKED_RENDERER_WEBGL
                        return 'NVIDIA GeForce RTX 3060/PCIe/SSE2';
                    default:
                        return originalGetParameter.call(this, pname);
                }
            };
        }
        
        return context;
    };
    
    // === CAMADA 5: WEBRTC BLOCK ===
    window.RTCPeerConnection = undefined;
    window.webkitRTCPeerConnection = undefined;
    window.mozRTCPeerConnection = undefined;
    
    // === CAMADA 6: HUMAN BEHAVIOR SYSTEM ===
    class HumanBehavior {
        constructor() {
            this.mouseX = window.innerWidth / 2;
            this.mouseY = window.innerHeight / 2;
            this.lastMove = Date.now();
        }
        
        async moveTo(x, y, duration = 1000) {
            const startX = this.mouseX;
            const startY = this.mouseY;
            const startTime = Date.now();
            
            while (Date.now() - startTime < duration) {
                const progress = (Date.now() - startTime) / duration;
                const eased = this.easeOutCubic(progress);
                
                // Calcula posição com curva de Bezier
                const currentX = startX + (x - startX) * eased;
                const currentY = startY + (y - startY) * eased;
                
                // Adiciona tremor humano
                const tremorX = (Math.random() - 0.5) * 1.5;
                const tremorY = (Math.random() - 0.5) * 1.5;
                
                const event = new MouseEvent('mousemove', {
                    view: window,
                    bubbles: true,
                    cancelable: true,
                    clientX: currentX + tremorX,
                    clientY: currentY + tremorY
                });
                
                document.dispatchEvent(event);
                
                this.mouseX = currentX;
                this.mouseY = currentY;
                
                // Delay entre movimentos (variavel)
                await new Promise(resolve => 
                    setTimeout(resolve, 10 + Math.random() * 15)
                );
            }
        }
        
        easeOutCubic(t) {
            return 1 - Math.pow(1 - t, 3);
        }
        
        async humanClick(element) {
            const rect = element.getBoundingClientRect();
            const targetX = rect.left + rect.width / 2;
            const targetY = rect.top + rect.height / 2;
            
            // Move até o elemento em 3 etapas
            await this.moveTo(targetX - 30, targetY - 30, 400);
            await this.moveTo(targetX - 10, targetY - 10, 200);
            await this.moveTo(targetX, targetY, 100);
            
            // Aguarda um pouco antes de clicar
            await new Promise(resolve => setTimeout(resolve, 100 + Math.random() * 150));
            
            // Simula clique humano
            element.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
            await new Promise(resolve => setTimeout(resolve, 50 + Math.random() * 80));
            element.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
            element.dispatchEvent(new MouseEvent('click', { bubbles: true }));
            
            // Move para fora após clicar
            await this.moveTo(targetX + 20, targetY + 20, 200);
        }
        
        async humanType(element, text) {
            element.focus();
            
            for (let i = 0; i < text.length; i++) {
                const char = text[i];
                
                // Chance de pausa natural (5%)
                if (Math.random() < 0.05 && i > 3) {
                    await new Promise(resolve => 
                        setTimeout(resolve, 200 + Math.random() * 400)
                    );
                }
                
                // Chance de erro e correção (2%)
                if (Math.random() < 0.02 && i > 3) {
                    // Digita caractere errado
                    const wrongChar = String.fromCharCode(97 + Math.floor(Math.random() * 26));
                    element.value += wrongChar;
                    element.dispatchEvent(new Event('input', { bubbles: true }));
                    
                    await new Promise(resolve => 
                        setTimeout(resolve, 100 + Math.random() * 200)
                    );
                    
                    // Apaga
                    element.value = element.value.slice(0, -1);
                    element.dispatchEvent(new Event('input', { bubbles: true }));
                    
                    await new Promise(resolve => 
                        setTimeout(resolve, 50 + Math.random() * 100)
                    );
                }
                
                // Digita caractere correto
                element.value += char;
                
                // Dispara eventos
                element.dispatchEvent(new Event('input', { bubbles: true }));
                element.dispatchEvent(new KeyboardEvent('keydown', { key: char }));
                element.dispatchEvent(new KeyboardEvent('keypress', { key: char }));
                element.dispatchEvent(new KeyboardEvent('keyup', { key: char }));
                
                // Delay entre teclas (humano)
                await new Promise(resolve => 
                    setTimeout(resolve, 60 + Math.random() * 90)
                );
            }
        }
    }
    
    // Inicializa sistema de comportamento
    window.humanBehavior = new HumanBehavior();
    
    console.log('[Quantum Fingerprint 2026] Sistema ativado');
})();
"""

# ===================== SISTEMA DE COMPORTAMENTO HUMANO PYTHON =====================
class HumanSimulator:
    """Simula comportamento humano no nível do Playwright"""
    
    @staticmethod
    async def random_delay(min_ms=100, max_ms=3000):
        """Delay aleatório entre ações"""
        delay = random.uniform(min_ms, max_ms) / 1000
        await asyncio.sleep(delay)
    
    @staticmethod
    async def simulate_reading(page):
        """Simula leitura da página"""
        print("[HUMAN] Simulando leitura da página...")
        
        # Rola aleatoriamente
        scroll_actions = random.randint(2, 5)
        for _ in range(scroll_actions):
            scroll_amount = random.randint(200, 800)
            scroll_duration = random.randint(300, 1200)
            
            await page.evaluate(f"""
                window.scrollBy({{
                    top: {scroll_amount},
                    behavior: 'smooth'
                }});
            """)
            
            await asyncio.sleep(scroll_duration / 1000)
            
            # Pequena pausa após rolar
            await HumanSimulator.random_delay(200, 800)
    
    @staticmethod
    async def simulate_mouse_movement(page):
        """Simula movimento de mouse aleatório"""
        await page.evaluate("""
            async () => {
                const moves = 5 + Math.floor(Math.random() * 8);
                for (let i = 0; i < moves; i++) {
                    const x = Math.random() * window.innerWidth;
                    const y = Math.random() * window.innerHeight;
                    await window.humanBehavior.moveTo(x, y, 500 + Math.random() * 1000);
                    await new Promise(r => setTimeout(r, 100 + Math.random() * 300));
                }
            }
        """)
    
    @staticmethod
    async def human_interaction_before_action(page):
        """Interação humana antes de uma ação importante"""
        await HumanSimulator.simulate_mouse_movement(page)
        
        await HumanSimulator.random_delay(500, 2000)
        
        if random.random() > 0.5:
            await HumanSimulator.simulate_reading(page)


def limpar_tela():
    os.system('cls' if os.name == 'nt' else 'clear')

def selecionar_configuracao():
    limpar_tela()
    print("╔══════════════════════════════════════════════════════════╗")
    print("║         CREAMCRACKER - HUMAN BEHAVIOR EDITION           ║")
    print("║        Amazon Account Generator 2026                    ║")
    print("╚══════════════════════════════════════════════════════════╝")
    print()
    
    while True:
        try:
            n = input("Quantas contas criar? (1-10 recomendo): ").strip()
            if n.isdigit() and 1 <= int(n) <= 1000:
                return int(n)
            print("Digite um número de 1 a 1000!")
        except:
            pass

async def gerar_numero_brasileiro():
    async with numero_lock:
        url = (
            f"https://hero-sms.com/stubs/handler_api.php"
            f"?api_key={SMS_ACTIVATE_API_KEY}"
            f"&action=getNumber"
            f"&service={AMAZON_SERVICE_CODE}"
            f"&country={BRAZIL_COUNTRY_CODE}"
        )
        for tentativa in range(8):
            try:
                r = requests.get(url, timeout=30)
                if "ACCESS_NUMBER" in r.text:
                    _, aid, phone = r.text.split(":")
                    print(f"[+] Número obtido: +55{phone} (tentativa {tentativa+1})")
                    return {
                        "phone_number": phone,
                        "activation_id": aid
                    }
                await asyncio.sleep(5)
            except Exception as e:
                print(f"[-] Erro SMS: {e}")
                await asyncio.sleep(5)
        return None

def gerar_nome_completo():
    return fake.name()

def gerar_senha():
    return fake.password(length=16, special_chars=True, digits=True, upper_case=True, lower_case=True)

def gerar_configuracao_navegador():
    user_agents = [
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36 Edg/132.0.0.0",
    ]
    viewports = [
        {"width": 1366, "height": 768},
        {"width": 1920, "height": 1080},
        {"width": 1440, "height": 900},
        {"width": 1536, "height": 864},
    ]
    timezones = [
        "America/Sao_Paulo",
        "America/Manaus", 
        "America/Fortaleza",
        "America/Recife",
        "America/Bahia"
    ]

    return {
        "user_agent": random.choice(user_agents),
        "viewport": random.choice(viewports),
        "timezone": random.choice(timezones),
        "locale": "pt-BR",
        "slow_mo": random.randint(150, 400)
    }

# ============================================================================
# FUNÇÕES DE NAVEGAÇÃO - COM COMPORTAMENTO HUMANO
# ============================================================================

async def abrir_amazon_brasil(page):
    """Abrir Amazon na página inicial e navegar para registro"""

    try:
  

        registro_url = "https://www.amazon.com.br/ap/register?showRememberMe=true&openid.pape.max_auth_age=0&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&siteState=132-4197341-6745562&language=pt_BR&pageId=amzn_prime_video_ww&openid.return_to=https%3A%2F%2Fna.primevideo.com%2F-%2Fpt%2Fauth%2Freturn%2Fref%3Dav_auth_ap%3F_t%3D1sgy8IC5LKTNW6Y4dabu9Mmf3twLJHNY6UEyeD6o5_9f1oAAAAAQAAAABpQSVycmF3AAAAAPgWC9WfHH8iB-olH_E9xQ%26language%3Dpt%26location%3D%2F-%2Fpt%2Foffers%2Fnonprimehomepage%3Fref_%253Ddv_web_force_root%2526language%253Dpt&prevRID=KDGSCWHDSKXWE4WFB7VK&openid.assoc_handle=amzn_prime_video_sso_br&openid.mode=checkid_setup&prepopulatedLoginId=&failedSignInCount=0&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0"

        try:
            await page.goto(registro_url, wait_until='domcontentloaded', timeout=10000)
            await asyncio.sleep(4)
            return True
        except Exception:
            return False

    except Exception:
        return False

async def digitar_nome_sobrenome(page, nome_completo):
    """Digitar nome e sobrenome (primeiro campo)"""
    seletores = [
        'input[id="ap_customer_name"]',
        'input[name="customerName"]',
        'input[placeholder="First and last name"]',
        'input[autocomplete="name"]',
        '#ap_customer_name'
    ]
    
    for seletor in seletores:
        try:
            elemento = page.locator(seletor).first
            if await elemento.count() > 0 and await elemento.is_visible():
                await elemento.click()
                await asyncio.sleep(0.5)
                await elemento.fill(nome_completo)
                print(f"Nome digitado: {seletor}")
                await asyncio.sleep(1)
                return True
        except:
            continue
    
    print("Campo de nome não encontrado")
    return False

async def digitar_numero_telefone(page, phone_number):
    """Digitar número de telefone no formato brasileiro"""
    numero_formatado = formatar_numero_brasileiro(phone_number)
    await asyncio.sleep(1)
    
    seletores = [
        'input[id="ap_phone_number"]',
        'input[name="ap_phone_number"]',
        'input[autocomplete="username"]',
        'input[type="email"]',
        '#ap_email_login'
    ]
    
    for seletor in seletores:
        try:
            elemento = page.locator(seletor)
            if await elemento.count() > 0:
                await elemento.click()
                await elemento.fill(numero_formatado)
                await asyncio.sleep(1)
                return True
        except:
            continue
    
    print("Campo de telefone não encontrado")
    return False

def formatar_numero_brasileiro(phone_number):
    """Remove +55 e deixa só o número puro para o campo da Amazon"""
    numero_limpo = re.sub(r'[^\d]', '', phone_number)

    # Remove prefixo 55 se existir
    if numero_limpo.startswith("55"):
        numero_limpo = numero_limpo[2:]

    return numero_limpo


async def digitar_senha(page, senha="123456"):
    """Digitar senha"""
    await asyncio.sleep(1)
    seletores_senha = [
        'input[id="ap_password"]',
        'input[name="password"]',
        'input[placeholder="Pelo menos 6 caracteres"]',
        'input[autocomplete="new-password"]',
        'input[type="password"]',
        '#ap_password'
    ]
    
    for seletor in seletores_senha:
        try:
            elemento = page.locator(seletor)
            if await elemento.count() > 0:
                await elemento.click()
                await elemento.fill(senha)
                break
        except:
            continue
    
    await asyncio.sleep(1)
    return True

async def redigitar_senha(page, senha="123456"):
    """Redigitar senha (confirmação)"""
    seletores = [
        'input[id="ap_password_check"]',
        'input[name="passwordCheck"]',
        'input[autocomplete="new-password"]',
        '#ap_password_check'
    ]
    
    for seletor in seletores:
        try:
            elemento = page.locator(seletor).first
            if await elemento.count() > 0 and await elemento.is_visible():
                await elemento.click()
                await asyncio.sleep(0.5)
                await elemento.fill(senha)
                await asyncio.sleep(1)
                return True
        except:
            continue
    
    print("Campo de confirmação não encontrado")
    return False



async def clicar_continue_final(page):
    """Clicar no botão continue final após senha"""
    print("Clicando no botão continue final...")
    seletores = [
        'input[id="continue"]',
        'input[aria-labelledby="auth-continue-announce"]',
        'input[class="a-button-input"][type="submit"]',
        'input[type="submit"]',
        'input.a-button-input[type="submit"]',
        'button[type="submit"]',
        'button:has-text("Continue")',
        'button:has-text("Continuar")',
        'button:has-text("Criar conta")',
        'button:has-text("Create account")'
    ]
    
    for seletor in seletores:
        try:
            elemento = page.locator(seletor)
            if await elemento.count() > 0 and await elemento.is_visible():
                await elemento.click()
                print(f"Continue final clicado: {seletor}")
                await asyncio.sleep(1)
                return True
        except:
            continue
    
    print("Botão continue final não encontrado")
    return False

# ============================================================================
# FUNÇÕES DE CAPTCHA
# ============================================================================

async def detectar_captcha(page):
    """Detectar CAPTCHA com aguardo maior para proxy"""
    await asyncio.sleep(5)
    for _ in range(30):
        seletores = [
            '#captcha-container', '.captcha-container', '[data-captcha]',
            'iframe[src*="captcha"]', 'iframe[src*="challenge"]', '.captcha',
            '#captcha', '[id*="captcha"]', '[class*="captcha"]',
            'canvas[width="324"][height="324"]', '#aacb-waf-box',
            '.amzn-captcha-modal', 'iframe[src*="amazon"]',
            'div[class*="captcha"]', 'section[class*="captcha"]'
        ]
        
        for seletor in seletores:
            try:
                elementos = page.locator(seletor)
                count = await elementos.count()
                if count > 0:
                    for i in range(count):
                        if await elementos.nth(i).is_visible():
                            return True
            except:
                continue
        await asyncio.sleep(1)
    return False

async def aguardar_captcha_manual(page):
    """Aguardar resolução manual do CAPTCHA"""
    print("Aguardando resolução manual do CAPTCHA...")
    print("Resolva o CAPTCHA manualmente na janela do navegador")
    print("Tempo limite: 40 segundos")
    
    for tentativa in range(40):
        try:
            captcha_presente = False
            seletores = [
                '#captcha-container', '.captcha-container', '[data-captcha]',
                'iframe[src*="captcha"]', 'iframe[src*="challenge"]', '.captcha',
                '#captcha', '[id*="captcha"]', '[class*="captcha"]',
                'canvas[width="324"][height="324"]', '#aacb-waf-box',
                '.amzn-captcha-modal', 'iframe[src*="amazon"]',
                'div[class*="captcha"]', 'section[class*="captcha"]'
            ]
            
            for seletor in seletores:
                try:
                    elementos = page.locator(seletor)
                    count = await elementos.count()
                    if count > 0:
                        for i in range(count):
                            if await elementos.nth(i).is_visible():
                                captcha_presente = True
                                break
                        if captcha_presente:
                            break
                except:
                    continue
            
            if not captcha_presente:
                print("CAPTCHA resolvido pelo usuário!")
                await asyncio.sleep(5)
                return True
            
            await asyncio.sleep(1)
            if tentativa % 10 == 0 and tentativa > 0:
                print(f"Aguardando... {tentativa}/40 segundos")
                        
        except Exception:
            await asyncio.sleep(1)
            continue
        
    print("Timeout: CAPTCHA não foi resolvido em 40 segundos")
    return False

# ============================================================================
# FUNÇÕES DE OTP
# ============================================================================

async def aguardar_otp_e_preencher(page, activation_id, phone_number):
    """Aguardar OTP e preencher"""
    print("Aguardando OTP...")
   
    base_url = "https://hero-sms.com/stubs/handler_api.php"  # ← única mudança: URL do HeroSMS
    for tentativa in range(20):
        try:
            params = {
                "api_key": SMS_ACTIVATE_API_KEY,  # continua usando a mesma variável (coloque a chave do HeroSMS nela)
                "action": "getStatus",
                "id": activation_id
            }
            response = requests.get(base_url, params=params, timeout=20)
            print(f"Status: {response.text}")
            if "STATUS_OK" in response.text:
                codigo = response.text.split(":")[1]
                print(f"Código OTP: {codigo}")
                seletores_otp = [
                    '#cvf-input-code',
                    'input[name="code"]',
                    'input[name="verificationCode"]',
                    'input[name="otp"]',
                    'input[id="verificationCode"]',
                    'input[id="otp"]',
                    'input[type="text"]'
                ]
                for seletor in seletores_otp:
                    try:
                        elemento = page.locator(seletor)
                        if await elemento.count() > 0 and await elemento.is_visible():
                            await elemento.click()
                            await elemento.fill(codigo)
                            print(f"OTP preenchido em: {seletor}")
                            await asyncio.sleep(1)
                            await clicar_continuar_otp(page)
                            return True
                    except:
                        continue
                print("Campo OTP não encontrado")
                return False
            elif "STATUS_WAIT_CODE" in response.text:
                print(f"Aguardando... tentativa {tentativa + 1}/20")
                await asyncio.sleep(5)
            else:
                print(f"Status inesperado: {response.text}")
                await asyncio.sleep(5)
        except Exception as e:
            print(f"Erro: {e}")
            await asyncio.sleep(5)
    print("OTP não recebido")
    return False

async def codepais(page, codigo="BR"):
    try:
        # abre o dropdown
        dropdown = page.locator('span.a-dropdown-prompt').first
        await dropdown.click()
        await asyncio.sleep(0.2)
    except:
        print("❌ Não conseguiu abrir o dropdown")
        return False

    # tenta por data-value (o mais confiável)
    seletor = f'a.a-dropdown-link[data-value*="{codigo}"]'
    opcao = page.locator(seletor).first

    if await opcao.count() > 0:
        await opcao.click(force=True)
        print("✔ País selecionado (via data-value):", codigo)
        return True

    # fallback por texto "Brazil"
    opcao = page.locator('a.a-dropdown-link', has_text="Brazil").first
    if await opcao.count() > 0:
        await opcao.click(force=True)
        print("✔ País selecionado (via texto): Brazil")
        return True

    # fallback por texto "+55"
    opcao = page.locator('a.a-dropdown-link', has_text="+55").first
    if await opcao.count() > 0:
        await opcao.click(force=True)
        print("✔ País selecionado (via +55)")
        return True

    print("❌ Não achou o país BR")
    return False




async def clicar_continuar_otp(page):
    """Clicar em continuar após OTP"""
    seletores = [
        'input[aria-label="Verificar o botão do código de verificação"]',
        'input[aria-describedby="legalTextRow"]',
        'button:has-text("Continue")', 'button:has-text("Continuar")',
        'button:has-text("Verify")', 'button:has-text("Verificar")',
        'button:has-text("Submit")', 'button:has-text("Enviar")',
        'button[type="submit"]', 'input[type="submit"]'
    ]
    
    for seletor in seletores:
        try:
            elemento = page.locator(seletor)
            if await elemento.count() > 0 and await elemento.is_visible():
                await elemento.click()
                print(f"Continuar clicado: {seletor}")
                await asyncio.sleep(1)
                return True
        except:
            continue
    
    print("Botão continuar não encontrado")
    return False

# ============================================================================
# FUNÇÕES DE WALLET E COOKIES
# ============================================================================

async def acessar_wallet_amazon(page):
    """Acessar a página da wallet da Amazon para obter cookies atualizados"""
    print("Acessando wallet da Amazon...")
    wallet_urls = [
        "https://www.amazon.com.br/gp/gc/balance",
        "https://www.amazon.com.br/gp/gc/home",
        "https://www.amazon.com.br/gc/balance",
        "https://www.amazon.com.br/gc/home",
        "https://www.amazon.com.br/gp/css/gc/balance"
    ]
    
    for url in wallet_urls:
        try:
            print(f"Tentando acessar: {url}")
            await page.goto(url, wait_until='domcontentloaded', timeout=20000)
            await asyncio.sleep(3)
            current_url = page.url.lower()
            
            if "signin" in current_url or "ap/signin" in current_url:
                print("Redirecionado para login, tentando ir para home...")
                await page.goto("https://www.amazon.com.br/", wait_until='domcontentloaded', timeout=15000)
                await asyncio.sleep(2)
                await page.goto(url, wait_until='domcontentloaded', timeout=20000)
                await asyncio.sleep(3)
            
            wallet_encontrada = False
            wallet_selectors = [
                'text="Gift Card Balance"', 'text="Saldo do Cartão Presente"',
                'text="Gift Cards"', 'text="Cartões Presente"',
                '[data-testid*="gift"]', '[id*="gc"]', '[class*="gift"]',
                'h1:has-text("Gift")', 'h1:has-text("Cartão")'
            ]
            
            for selector in wallet_selectors:
                try:
                    elements = page.locator(selector)
                    if await elements.count() > 0:
                        wallet_encontrada = True
                        print(f"Wallet identificada: {selector}")
                        break
                except:
                    continue
            
            if "gc" in current_url or "gift" in current_url:
                wallet_encontrada = True
            
            if wallet_encontrada:
                print(f"Wallet acessada com sucesso: {url}")
                await asyncio.sleep(2)
                return True
            else:
                print(f"Página acessada (sem indicadores): {url}")
                await asyncio.sleep(2)
                return True
            
        except Exception as e:
            print(f"Erro ao acessar {url}: {str(e)[:80]}")
            continue
    
    print("Não foi possível acessar wallet, continuando com cookies atuais...")
    return False

async def capturar_cookies_wallet(page):
    """Captura cookies da página atual"""
    print("Capturando cookies...")
    try:
        cookies = await page.context.cookies()
        if not cookies:
            print("Nenhum cookie encontrado")
            return None
        
        session_token = None
        outros_cookies = []
        for cookie in cookies:
            cookie_str = f"{cookie['name']}={cookie['value']}"
            if cookie['name'] == 'session-token':
                session_token = cookie_str
            else:
                outros_cookies.append(cookie_str)
        
        cookies_string = session_token + "; " + "; ".join(outros_cookies) if session_token else "; ".join(outros_cookies)
        print(f"Cookies capturados ({len(cookies)} cookies)")
        return cookies_string
    except Exception as e:
        print(f"Erro ao capturar cookies: {e}")
        return None

def salvar_cookies_arquivo(cookies_string, phone_number):
    """Salva cookies em arquivo cookies2.txt"""
    if not cookies_string:
        return False
    try:
        os.makedirs('dados', exist_ok=True)
        with open('dados/cookies.txt', 'a', encoding='utf-8') as f:
            f.write(f"{cookies_string}\n")
        print(f"Cookies salvos em: dados/cookies.txt")
        return True
    except Exception as e:
        print(f"Erro ao salvar cookies: {e}")
        return False

# ============================================================================
# FUNÇÃO PRINCIPAL DE CRIAÇÃO DE CONTA
# ============================================================================

async def criar_conta_amazon(thread_id=1, posicao_janela=None, conta_id=1):
    """Criar conta Amazon"""
    numero_info = await gerar_numero_brasileiro()
    if not numero_info:
        return False
    
    phone_number = numero_info["phone_number"]
    activation_id = numero_info["activation_id"]
    nome_completo = gerar_nome_completo()
    temp_dir = tempfile.mkdtemp(prefix=f"chrome_profile_{conta_id}_")
    
    try:
        async with async_playwright() as p:
            config_navegador = gerar_configuracao_navegador()
            if posicao_janela:
                config_navegador["posicao"] = posicao_janela
            
            proxy_config = {
                "server": "http://proxy.smartproxy.net:3120",
                "username": "smart-y7z712uc9dh1_area-BR",
                "password": "1q7tvnhYOPjTlbhm"
            }
            #tua proxy cade
            extension_path = r'C:\xampp\htdocs\chk\Gerador-amz\extensions\pgojnojmmhpofjgdmaebadhbocahppod'
            
            context = await p.chromium.launch_persistent_context(
                temp_dir,
                headless=False,
                slow_mo=config_navegador["slow_mo"],
                proxy=proxy_config,
                args=[
                    '--no-sandbox', '--disable-dev-shm-usage',
                    '--disable-blink-features=AutomationControlled',
                    '--disable-web-security', '--disable-features=VizDisplayCompositor',
                    '--disable-plugins', '--disable-gpu', '--no-first-run',
                    '--no-default-browser-check', '--disable-default-apps',
                    f'--user-agent={config_navegador["user_agent"]}',
                    f'--timezone={config_navegador["timezone"]}',
                    f'--lang={config_navegador["locale"]}',
                    f'--window-position={config_navegador["posicao"]["x"]},{config_navegador["posicao"]["y"]}',
                    f'--window-size={config_navegador["viewport"]["width"]},{config_navegador["viewport"]["height"]}',
                    f'--load-extension={extension_path}',
                    f'--disable-extensions-except={extension_path}'
                ],
                viewport=config_navegador["viewport"],
                user_agent=config_navegador["user_agent"],
                locale=config_navegador["locale"],
                timezone_id=config_navegador["timezone"]
            )
        
            page = await context.new_page()
            
            await page.set_extra_http_headers({
                'User-Agent': config_navegador["user_agent"],
                'Accept-Language': 'pt-BR,pt;q=0.9,en;q=0.8',
                'Accept-Encoding': 'gzip, deflate, br',
                'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
            })
            
            try:
                if not await abrir_amazon_brasil(page): return False
                if not await digitar_numero_telefone(page, phone_number): return False
                if not await codepais(page, "BR +55"): return False
                if not await digitar_nome_sobrenome(page, nome_completo): return False
                if not await digitar_senha(page): return False
                if not await clicar_continue_final(page): return False
                # Nova linha ↓
                if not await aguardar_otp_e_preencher(page, activation_id, phone_number): return False
                
                await asyncio.sleep(3)
                await acessar_wallet_amazon(page)
                cookies_string = await capturar_cookies_wallet(page)
                
                os.makedirs('dados', exist_ok=True)
                with open('dados/contas-amazon.txt', 'a', encoding='utf-8') as f:
                    f.write(f"+{phone_number} 123456\n")
                print("Conta salva em: dados/contas-amazon.txt")
                
                if cookies_string:
                    salvar_cookies_arquivo(cookies_string, phone_number)
                
                print(f"CONTA #{conta_id} - CRIADA COM SUCESSO!")
                if cookies_string:
                    print("Cookies capturados e salvos!")
                
                await asyncio.sleep(5)
                await context.close()
                return True
                
            except Exception as e:
                print(f"Erro durante criação: {e}")
                await context.close()
                return False
                
    finally:
        def delete_temp():
            for _ in range(10):
                try:
                    shutil.rmtree(temp_dir, ignore_errors=True)
                    break
                except Exception:
                    time.sleep(1)
        threading.Thread(target=delete_temp, daemon=True).start()

# ============================================================================
# EXECUÇÃO PRINCIPAL - 2 EM 2
# ============================================================================

async def main():
    """Sistema principal com até 5 navegadores simultâneos"""
    config = selecionar_configuracao()
    if config is None:
        return
    
    num_contas = config
    print(f"Criando {num_contas} conta{'s' if num_contas > 1 else ''} (5 em 5)...")
    print("=" * 60)
    
    contas_sucesso = 0
    contas_falha = 0
    sem = asyncio.Semaphore(5)
    
    async def create_account(conta_id):
        nonlocal contas_sucesso, contas_falha  # <<< CORRIGIDO: NONLOCAL NO INÍCIO
        
        async with sem:
            slot = (conta_id - 1) % 1
            posicao = {"x": 100 + slot * 700, "y": 100}
            thread_id = slot + 1
            
            print(f"CONTA #{conta_id} - Iniciando (slot {slot})...")
            
            try:
                sucesso = await criar_conta_amazon(thread_id=thread_id, posicao_janela=posicao, conta_id=conta_id)
                
                if sucesso:
                    contas_sucesso += 1
                    print(f"CONTA #{conta_id} - CRIADA COM SUCESSO!")
                else:
                    contas_falha += 1
                    print(f"CONTA #{conta_id} - FALHOU")
                
                delay = random.randint(0, 2)
                print(f"Aguardando {delay}s antes da próxima...")
                await asyncio.sleep(delay)
                
            except Exception as e:
                contas_falha += 1
                print(f"CONTA #{conta_id} - ERRO: {e}")
    
    tasks = [create_account(i) for i in range(1, num_contas + 1)]
    await asyncio.gather(*tasks)
    
    print(f"\nSISTEMA FINALIZADO:")
    print(f"Sucessos: {contas_sucesso}")
    print(f"Falhas: {contas_falha}")
    print(f"Total: {num_contas} contas processadas")

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