#!/usr/bin/env python3
"""
Busca todos os contatos do location e filtra pelos critérios do lançamento.
Usa paginação cursor-based (startAfter / startAfterId).
"""

import requests
import time
import re
import json

TOKEN = "pit-cb07507e-3712-4f3e-8c24-fafc8a8430ba"
LOCATION_ID = "W7PGxpfbsFaEEUoQOtUb"
BASE_URL = "https://services.leadconnectorhq.com"

HEADERS = {
    "Authorization": f"Bearer {TOKEN}",
    "Version": "2021-07-28",
    "Content-Type": "application/json"
}

TAGS_ALVO = {
    "waitlist-photorf2-v2",
    "lancamento-cloudphotorf2-quente",
    "lancamento-cloudphotorf2-morno",
    "lancamento-cloudphotorf2-frio",
}

TAG_EXCLUSAO = "excluir-disparo-hoje-20261007"

def phone_valid(phone):
    if not phone:
        return False
    # Remove espaços, hifens, parênteses
    p = re.sub(r'[\s\-\(\)]', '', str(phone))
    # +55 + DDD (2 dígitos) + número (8 ou 9 dígitos) = 13 ou 14 chars totais
    return bool(re.match(r'^\+55\d{10,11}$', p))

def fetch_all_contacts():
    """Busca todos os contatos do location via paginação cursor"""
    all_contacts = []
    url = f"{BASE_URL}/contacts/?locationId={LOCATION_ID}&limit=100"
    page = 0
    
    while url:
        page += 1
        resp = requests.get(url, headers=HEADERS)
        
        if resp.status_code != 200:
            print(f"  ERRO página {page}: {resp.status_code} {resp.text[:300]}")
            break
        
        data = resp.json()
        contacts = data.get('contacts', [])
        meta = data.get('meta', {})
        
        all_contacts.extend(contacts)
        
        if page % 10 == 0 or page == 1:
            total = meta.get('total', '?')
            print(f"  Página {page}: {len(contacts)} contatos | Acumulado: {len(all_contacts)}/{total}")
        
        next_url = meta.get('nextPageUrl')
        url = next_url if next_url else None
        
        if url:
            time.sleep(0.15)
    
    return all_contacts

print("=== BUSCANDO TODOS OS CONTATOS ===")
all_contacts = fetch_all_contacts()
print(f"\nTotal bruto buscado: {len(all_contacts)}")

# Filtrar
elegiveis = []
excluidos_por_tag = []
sem_tag_lancamento = 0
excluidos_sem_tel = []

for c in all_contacts:
    contact_tags = set(c.get('tags') or [])
    
    # Tem alguma tag alvo?
    if not contact_tags.intersection(TAGS_ALVO):
        sem_tag_lancamento += 1
        continue
    
    # Verificar tag de exclusão
    if TAG_EXCLUSAO in contact_tags:
        excluidos_por_tag.append({
            'id': c.get('id'),
            'name': f"{c.get('firstName','')} {c.get('lastName','')}".strip(),
            'tags': list(contact_tags)
        })
        continue
    
    # Verificar telefone
    phone = c.get('phone', '')
    if not phone_valid(phone):
        excluidos_sem_tel.append({
            'id': c.get('id'),
            'name': f"{c.get('firstName','')} {c.get('lastName','')}".strip(),
            'phone': phone,
            'tags': list(contact_tags)
        })
        continue
    
    elegiveis.append(c)

print(f"\n=== RESULTADO DOS FILTROS ===")
print(f"Total contatos buscados: {len(all_contacts)}")
print(f"Sem tag de lançamento (ignorados): {sem_tag_lancamento}")
print(f"Com alguma tag de lançamento: {len(all_contacts) - sem_tag_lancamento}")
print(f"  Excluídos por tag {TAG_EXCLUSAO}: {len(excluidos_por_tag)}")
print(f"  Excluídos sem telefone BR válido: {len(excluidos_sem_tel)}")
print(f"  ELEGÍVEIS FINAIS: {len(elegiveis)}")

# Análise de tags nos elegíveis
tag_count = {}
for c in elegiveis:
    for t in (c.get('tags') or []):
        if t in TAGS_ALVO:
            tag_count[t] = tag_count.get(t, 0) + 1
print(f"\nDistribuição de tags nos elegíveis:")
for t, n in sorted(tag_count.items(), key=lambda x: -x[1]):
    print(f"  {t}: {n}")

# Salvar
base = '/opt/mia/workspace/clientes/px3lab/mapeamento_leads_lancamento_1007'
with open(f'{base}/elegiveis.json', 'w') as f:
    json.dump(elegiveis, f, ensure_ascii=False, indent=2)

with open(f'{base}/sem_telefone.json', 'w') as f:
    json.dump(excluidos_sem_tel, f, ensure_ascii=False, indent=2)

with open(f'{base}/excluidos_por_tag.json', 'w') as f:
    json.dump(excluidos_por_tag, f, ensure_ascii=False, indent=2)

print(f"\nArquivos salvos em {base}")
print(f"\nPrimeiros 5 elegíveis:")
for c in elegiveis[:5]:
    print(f"  {c.get('id')} | {c.get('firstName','')} {c.get('lastName','')} | {c.get('phone','')} | tags: {[t for t in (c.get('tags') or []) if t in TAGS_ALVO]}")

