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

# --- FUNÇÃO DE NOMENCLATURA ---
def gerar_nome_arquivo(nome_cliente, url_texto):
    # 1. Tenta achar padrão de paginação (p=1, p=2)
    match = re.search(r'[#&?]p=(\d+)', url_texto)
    
    if match:
        sufixo = f"p{match.group(1)}"
    else:
        # 2. Se não achar, limpa a URL para usar como nome
        limpo = url_texto.replace("https://", "").replace("http://", "").replace("www.", "")
        limpo = limpo.strip().strip("/")
        # Substitui caracteres estranhos por underline
        sufixo = re.sub(r'[^\w\-_]', '_', limpo)
        
        if not sufixo:
            sufixo = "home"
            
    return f"{nome_cliente}_{sufixo}.png"

def processar_pagina_individual(page, pasta_destino, nome_arquivo_final):
    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=60000)
        time.sleep(5)

        # Tenta trocar snapshot se botão existir
        try:
            if page.locator("#heatmapChangeScreenshotButton").is_visible():
                print("   📸 Trocando snapshot...")
                page.locator("#heatmapChangeScreenshotButton").click()
                page.wait_for_selector("text=Escolha uma captura de tela", timeout=10000)
                time.sleep(2)
                page.locator("text=Selecionar >> visible=true").first.click()
                print("   ⏳ Snapshot trocado.")
        except: pass
        
        print("   ⏳ Aguardando 25s para renderização COMPLETA...")
        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']

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

        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:
        page.click("text=Mapas De Calor", timeout=15000)
        page.wait_for_selector("text=Visitas à página", timeout=30000)
        time.sleep(2)
        return True
    except Exception as e:
        print(f"⚠️ Erro ao navegar: {e}")
        return False

# --- FUNÇÃO NOVA: GERA A LISTA PARA O WORDPRESS ---
def gerar_lista_json(pasta_cliente):
    """Gera um JSON com todos os arquivos PNG da pasta para o site ler"""
    try:
        arquivos = [f for f in os.listdir(pasta_cliente) if f.endswith(".png") and "erro_" not in f]
        
        # Ordena alfabeticamente para ficar organizado no menu
        arquivos.sort()
        
        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"📝 Lista de imagens gerada: {caminho_json}")
    except Exception as e:
        print(f"❌ Erro ao gerar JSON da lista: {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 CLIENTE (SITES): {nome_cliente}")
    
    with sync_playwright() as p:
        # IMPORTANTE: headless=True para rodar no servidor
        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):
            print("❌ Falha crítica ao acessar dashboard.")
            browser.close()
            return
        
        seletor_linhas = "text=https:// >> visible=true"
        contagem = page.locator(seletor_linhas).count()
        print(f"📋 Total de heatmaps: {contagem}")

        for i in range(contagem):
            print(f"\n--- Item {i+1} de {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)
                print(f"🔗 Alvo: {texto_url} -> 💾 {nome_arquivo}")
                
                link_atual.click(force=True)
                processar_pagina_individual(page, pasta_cliente, nome_arquivo)
                
            except Exception as e:
                print(f"❌ Falha: {e}")
                continue

        browser.close()
    
    # --- GERA O ARQUIVO JSON NO FINAL ---
    gerar_lista_json(pasta_cliente)

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

    print(f"📂 Encontrados {len(lista_clientes)} clientes do tipo SITE.")
    
    for cliente in lista_clientes:
        processar_cliente(cliente)
        time.sleep(5)
