from playwright.sync_api import sync_playwright
import time
import re
import json
import os

def gerar_nome_arquivo(nome_cliente, url_texto):
    match = re.search(r'[#&?]p=(\d+)', url_texto)
    if match:
        numero = int(match.group(1))
        sufixo = f"p{numero}" 
    else:
        sufixo = "home"
    return f"{nome_cliente}_{sufixo}.png"

def processar_pagina_individual(page, pasta_destino, nome_arquivo_final, usar_segundo_snapshot=False):
    print(f"   🎨 Processando: {nome_arquivo_final}")
    caminho_completo = os.path.join(pasta_destino, nome_arquivo_final)
    
    try:
        print("   🎨 Aguardando iframe DO HEATMAP...")
        page.wait_for_selector("iframe >> visible=true", timeout=90000)
        time.sleep(5)

        # --- LÓGICA DE TROCA (Igual ao testesite.py) ---
        if usar_segundo_snapshot:
            print("   📸 FILTRO DETECTADO: Trocando snapshot...")
            try:
                if page.locator("#heatmapChangeScreenshotButton").is_visible():
                    page.locator("#heatmapChangeScreenshotButton").click()
                    page.wait_for_selector("text=Escolha uma captura de tela", timeout=10000)
                    time.sleep(2)
                    
                    print("      👆 Clicando na opção 'Selecionar'...")
                    # Clica no primeiro botão 'Selecionar' disponível (que é o segundo snapshot)
                    page.locator("text=Selecionar >> visible=true").first.click()
                    
                    try: page.wait_for_load_state("networkidle", timeout=15000)
                    except: pass
                    time.sleep(8)
                    print("      ✅ Snapshot trocado com sucesso.")
                else:
                    print("      ⚠️ Botão de troca não encontrado (pode ser o único snapshot).")
            except Exception as e:
                print(f"      ⚠️ Não foi possível trocar: {e}")
                # Não aborta, tenta tirar print do que tem
                try: page.keyboard.press("Escape")
                except: pass
                time.sleep(2)

        print("   ⏳ Aguardando renderização (25s)...")
        time.sleep(25)

        wrapper_locator = page.wait_for_selector(".heatmap-wrapper >> visible=true", timeout=60000)

        print("   🔧 Ajustando escala real (HD)...")
        dimensoes = page.evaluate("""() => {
            const wrapper = document.querySelector('.heatmap-wrapper');
            if (!wrapper) return null;
            const iframe = wrapper.querySelector('iframe');
            let realHeight = wrapper.offsetHeight;
            if (iframe && iframe.contentDocument && iframe.contentDocument.body) {
                const body = iframe.contentDocument.body;
                const html = iframe.contentDocument.documentElement;
                realHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
            }
            wrapper.style.transform = 'scale(1)';
            wrapper.style.transformOrigin = 'top left';
            wrapper.style.position = 'absolute';
            wrapper.style.top = '0px';
            wrapper.style.left = '0px';
            wrapper.style.margin = '0px';
            wrapper.style.height = realHeight + 'px';
            wrapper.style.overflow = 'hidden'; 
            wrapper.style.zIndex = '99999'; 
            const style = document.createElement('style');
            style.innerHTML = `.ms-Nav, .cl-top-bar, .ms-CommandBar, header, aside, .ms-Layer, #heatmapChangeScreenshotButton { display: none !important; } body { overflow: visible !important; background: #1b1b1b !important; }`;
            document.head.appendChild(style);
            return { width: wrapper.offsetWidth, height: realHeight };
        }""")

        if not dimensoes: raise Exception("Não foi possível manipular o wrapper.")

        largura_real = dimensoes['width']
        altura_real = dimensoes['height']
        if altura_real < 100: altura_real = 1080

        page.set_viewport_size({"width": int(largura_real), "height": int(altura_real)})
        time.sleep(3) 

        print(f"   📸 Salvando: {caminho_completo}")
        wrapper_locator.screenshot(path=caminho_completo)
        print("   ✅ Sucesso!")

    except Exception as e:
        print(f"   ❌ Erro nesta página: {e}")

def navegar_para_dashboard(page, url_dashboard):
    print("🔄 Carregando Dashboard...")
    page.set_viewport_size({"width": 1920, "height": 1080})
    page.goto(url_dashboard)
    page.wait_for_load_state("domcontentloaded") 
    time.sleep(3)
    try: page.locator("button:has-text('Aceitar')").click(timeout=2000)
    except: pass
    try: page.locator("button[aria-label='Close']").click(timeout=2000)
    except: pass
    try:
        if page.locator("text=Mapas De Calor").is_visible(): page.click("text=Mapas De Calor")
        page.wait_for_selector("text=Visitas à página", timeout=30000)
        time.sleep(2)
        btn_params = page.locator('[data-clarity-id="heatmapUrlParamToggleUnchecked"]')
        if btn_params.is_visible():
            if btn_params.get_attribute("aria-checked") == "false":
                btn_params.click()
                time.sleep(4) 
        return True
    except Exception as e:
        print(f"⚠️ Erro ao navegar: {e}")
        return False

def gerar_lista_json(pasta_cliente):
    """Gera lista ordenada para o WordPress"""
    try:
        arquivos = [f for f in os.listdir(pasta_cliente) if f.endswith(".png") and "erro_" not in f]
        def extrair_numero(texto):
            match = re.search(r'p(\d+)', texto)
            return int(match.group(1)) if match else 0
        arquivos.sort(key=extrair_numero)
        
        caminho_json = os.path.join(pasta_cliente, "lista_imagens.json")
        with open(caminho_json, "w", encoding="utf-8") as f:
            json.dump(arquivos, f)
        print(f"📝 JSON gerado: {caminho_json}")
    except Exception as e:
        print(f"❌ Erro JSON: {e}")

def processar_cliente(cliente):
    nome_cliente = cliente.get('nome', 'SemNome')
    url_dashboard = cliente.get('url')
    pasta_cliente = f"screenshots/{nome_cliente}"
    os.makedirs(pasta_cliente, exist_ok=True)
    
    print(f"\n🚀 INICIANDO REVISTA: {nome_cliente}")
    
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=True)
        context = browser.new_context(
            storage_state="auth_clarity.json",
            viewport={"width": 1920, "height": 1080},
            device_scale_factor=2
        )
        page = context.new_page()
        
        if not navegar_para_dashboard(page, url_dashboard):
            return
        
        seletor_linhas = "text=https:// >> visible=true"
        contagem = page.locator(seletor_linhas).count()
        print(f"📋 Encontrados: {contagem}")

        for i in range(contagem):
            print(f"\n--- Item {i+1}/{contagem} ---")
            if i > 0: navegar_para_dashboard(page, url_dashboard)
            
            try:
                links = page.locator(seletor_linhas)
                if i >= links.count(): break
                link_atual = links.nth(i)
                texto_url = link_atual.inner_text()
                
                nome_arquivo = gerar_nome_arquivo(nome_cliente, texto_url)
                
                # --- CORREÇÃO DO FILTRO ---
                # Removemos o 'https://' para garantir que bata com o texto da tela
                links_para_trocar = ["unicapagina.vercel.app/#p=3"]
                deve_trocar = any(link in texto_url for link in links_para_trocar)
                
                print(f"🔗 URL: {texto_url}")
                print(f"🔎 Filtro Ativo? {deve_trocar} (p/ p=3)")

                link_atual.click(force=True)
                processar_pagina_individual(page, pasta_cliente, nome_arquivo, usar_segundo_snapshot=deve_trocar)
                
            except Exception as e:
                print(f"❌ Falha: {e}")
                continue

        browser.close()
    
    gerar_lista_json(pasta_cliente)

if __name__ == "__main__":
    try:
        with open("clientes.json", "r", encoding="utf-8") as f:
            dados = json.load(f)
            clientes = dados.get("revistas", [])
    except: clientes = []

    for cliente in clientes:
        processar_cliente(cliente)
        time.sleep(5)
