import requests
import csv
import json
import time
import os

TOKEN = "pit-25f78b4f-4cc8-48f2-b8dc-73a98f851eaf"
LOCATION_ID = "W7PGxpfbsFaEEUoQOtUb"
headers = {
    "Authorization": f"Bearer {TOKEN}",
    "Version": "2021-07-28",
    "Content-Type": "application/json"
}

OUTPUT_PATH = "/opt/mia/workspace/clientes/px3lab/lista_contatos_whatsapp.csv"
OUTBOX_DIR = "/opt/mia-bot/outbox"

print("Iniciando busca de contatos no CRM Linkia PX3 Lab...")

contacts = []
page = 1

while True:
    r = requests.get(
        "https://services.leadconnectorhq.com/contacts/",
        headers=headers,
        params={"locationId": LOCATION_ID, "limit": 100, "page": page}
    )

    if r.status_code != 200:
        print(f"Erro na pagina {page}: {r.status_code} - {r.text}")
        break

    data = r.json()
    batch = data.get("contacts", [])

    if not batch:
        print(f"Pagina {page}: sem contatos, encerrando paginacao.")
        break

    contacts.extend(batch)
    print(f"Pagina {page}: {len(batch)} contatos carregados (total ate agora: {len(contacts)})")

    if len(batch) < 100:
        print("Ultima pagina atingida.")
        break

    page += 1
    time.sleep(0.3)  # respeitar rate limit

print(f"\nTotal de contatos carregados: {len(contacts)}")

# Filtrar apenas os que têm telefone preenchido
with_phone = []
for c in contacts:
    phone = (c.get("phone") or "").strip()
    if phone:
        with_phone.append(c)

print(f"Contatos COM telefone/WhatsApp: {len(with_phone)}")
print(f"Contatos SEM telefone: {len(contacts) - len(with_phone)}")

# Gerar CSV
with open(OUTPUT_PATH, "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["Nome", "Telefone", "Email", "Tags", "Data de criacao"])

    for c in with_phone:
        nome = f"{c.get('firstName', '')} {c.get('lastName', '')}".strip()
        telefone = (c.get("phone") or "").strip()
        email = (c.get("email") or "").strip()
        tags = ", ".join(c.get("tags", []) or [])
        criado_em = c.get("dateAdded") or c.get("createdAt") or ""
        # Formatar data se necessario
        if criado_em and "T" in criado_em:
            criado_em = criado_em.replace("T", " ").split(".")[0].split("+")[0]

        writer.writerow([nome, telefone, email, tags, criado_em])

print(f"\nCSV salvo em: {OUTPUT_PATH}")

# Enviar notificacao via outbox
ts1 = int(time.time() * 1e9)
msg = (
    f"Exportacao de contatos CRM Linkia PX3 Lab concluida.\n\n"
    f"Total de contatos na conta: {len(contacts)}\n"
    f"Contatos COM telefone/WhatsApp: {len(with_phone)}\n"
    f"Contatos SEM telefone: {len(contacts) - len(with_phone)}\n\n"
    f"O CSV esta sendo enviado logo abaixo."
)

fname1 = os.path.join(OUTBOX_DIR, f"{ts1}.json")
with open(fname1, "w") as f:
    json.dump({"text": msg}, f, ensure_ascii=False)

time.sleep(0.5)

ts2 = int(time.time() * 1e9)
fname2 = os.path.join(OUTBOX_DIR, f"{ts2}.json")
with open(fname2, "w") as f:
    json.dump({
        "document": OUTPUT_PATH,
        "caption": f"Lista de contatos PX3 Lab com WhatsApp - {len(with_phone)} contatos"
    }, f, ensure_ascii=False)

print("Notificacoes enviadas ao outbox.")
