#!/usr/bin/env python3
"""
Busca todos os contatos com tags de lançamento e filtra pelos critérios:
- TEM alguma das 4 tags de lançamento
- SEM a tag de exclusão
- Com telefone BR válido (+55 + DDD + 9+8 dígitos)
"""

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"

BR_PHONE_RE = re.compile(r'^\+55\d{10,11}$')

def phone_valid(phone):
    if not phone:
        return False
    # Remove espaços e caracteres extras
    p = re.sub(r'[\s\-\(\)]', '', str(phone))
    # Deve ter +55 + DDD (2 dígitos) + 9 dígitos (celular) = 14 chars
    # Ou +55 + DDD (2 dígitos) + 8 dígitos (fixo) = 13 chars
    # Missão pede: +55 + DDD + 9+8 dígitos = aceita 13 e 14
    return bool(BR_PHONE_RE.match(p))

def fetch_contacts_by_tag(tag):
    """Busca contatos por tag usando a API de contatos"""
    all_contacts = []
    page = 1
    limit = 100
    
    while True:
        url = f"{BASE_URL}/contacts/?locationId={LOCATION_ID}&tags={tag}&limit={limit}&skip={(page-1)*limit}"
        resp = requests.get(url, headers=HEADERS)
        
        if resp.status_code != 200:
            print(f"  ERRO tag={tag} page={page}: {resp.status_code} {resp.text[:200]}")
            break
        
        data = resp.json()
        contacts = data.get('contacts', [])
        
        if not contacts:
            break
            
        all_contacts.extend(contacts)
        
        total = data.get('meta', {}).get('total', 0)
        print(f"  tag={tag}: página {page}, got {len(contacts)}, total={total}, acumulado={len(all_contacts)}")
        
        if len(all_contacts) >= total or len(contacts) < limit:
            break
            
        page += 1
        time.sleep(0.2)
    
    return all_contacts

# Buscar contatos para cada tag
print("=== BUSCANDO CONTATOS POR TAG ===")
all_contacts_by_id = {}

for tag in TAGS_ALVO:
    print(f"\nBuscando tag: {tag}")
    contacts = fetch_contacts_by_tag(tag)
    for c in contacts:
        cid = c.get('id')
        if cid and cid not in all_contacts_by_id:
            all_contacts_by_id[cid] = c
    print(f"  Subtotal únicos até agora: {len(all_contacts_by_id)}")

print(f"\n=== TOTAL BRUTO (com tags de lançamento): {len(all_contacts_by_id)} ===")

# Filtrar
elegíveis = []
excluidos_por_tag = []
excluidos_sem_tel = []

for cid, c in all_contacts_by_id.items():
    contact_tags = [t.lower() if isinstance(t, str) else t for t in (c.get('tags') or [])]
    
    # Verificar tag de exclusão
    if TAG_EXCLUSAO in contact_tags:
        excluidos_por_tag.append(cid)
        continue
    
    # Verificar telefone
    phone = c.get('phone', '')
    if not phone_valid(phone):
        excluidos_sem_tel.append({
            'id': cid,
            'name': c.get('firstName', '') + ' ' + c.get('lastName', ''),
            'phone': phone,
            'tags': contact_tags
        })
        continue
    
    elegíveis.append(c)

print(f"\n=== RESULTADO DOS FILTROS ===")
print(f"Total com tags de lançamento: {len(all_contacts_by_id)}")
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(elegíveis)}")

# Salvar resultados
with open('/opt/mia/workspace/clientes/px3lab/mapeamento_leads_lancamento_1007/elegíveis.json', 'w') as f:
    json.dump(elegíveis, f, ensure_ascii=False, indent=2)

with open('/opt/mia/workspace/clientes/px3lab/mapeamento_leads_lancamento_1007/sem_telefone.json', 'w') as f:
    json.dump(excluidos_sem_tel, f, ensure_ascii=False, indent=2)

print("\nArquivos salvos: elegíveis.json, sem_telefone.json")
print(f"\nPrimeiros 5 elegíveis:")
for c in elegíveis[:5]:
    print(f"  {c.get('id')} | {c.get('firstName','')} {c.get('lastName','')} | {c.get('phone','')} | tags: {c.get('tags',[])}")

