#!/usr/bin/env python3
"""
Envia ao CRM os leads enriquecidos que ainda não estão no GHL (Sweet Angels).
Para cada lead: tenta encontrar no GHL → se não achar → cria contato + oportunidade com campos customizados.
"""

import json
import re
import sys
import time
from pathlib import Path

import requests

TOKEN       = "pit-0198bd77-3df3-4da6-93e7-bc50db3a5d86"
LOCATION_ID = "4z6Fjpgj2soAQZpu8Ddk"
PIPELINE_ID = "m0nDbsy8Pf7jW5Q9HyPj"
STAGE_ID    = "146d811e-84bb-41b0-a78c-e8c12d770a2f"
LEADS_PATH  = Path("/opt/mia/workspace/prospeccao_ativa/enriq_leads/f29a0543.json")
GHL_BASE    = "https://services.leadconnectorhq.com"

CAMPOS_MAP = {
    "cnpj":                  "OXuuJ2qaOS3Rft8yYYbM",
    "decisor_nome":          "yQn9XjbldhCuAQ2QBhEl",
    "decisor_cargo":         "42XmykBk5o1JzL2YgcHn",
    "linkedin_url":          "AhzLozPJlwPMrNRGmOvs",
    "instagram":             "hGNaQL49126z2H8R1nfl",
    "facebook":              "0wnPrPvRnH0TM4RDf5H9",
    "site":                  "HTynXy6CmQBknlpaGxBH",
    "fontes_enriquecimento": "5h6WOTvC5ZNrZhcuzQVL",
}

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


def so_digitos(s):
    return re.sub(r"\D", "", s or "")


def primeiro_telefone(raw):
    if not raw:
        return ""
    partes = re.split(r"[/,;|]", raw)
    for p in partes:
        d = so_digitos(p)
        if len(d) >= 8:
            return d
    return so_digitos(raw)


def buscar_contato(query):
    try:
        r = requests.get(
            f"{GHL_BASE}/contacts/",
            params={"locationId": LOCATION_ID, "query": query},
            headers=HEADERS,
            timeout=20,
        )
        if r.status_code == 200:
            return r.json().get("contacts", []) or []
    except Exception as e:
        print(f"    [erro busca] {e}")
    return []


def match_por_telefone(contatos, tel):
    if not tel:
        return None
    tail = tel[-8:]
    for c in contatos:
        for campo in ("phone", "phoneNumber"):
            v = so_digitos(c.get(campo) or "")
            if v and v.endswith(tail):
                return c
    return None


def match_por_nome(contatos, nome):
    alvo = (nome or "").strip().lower()
    if not alvo:
        return None
    for c in contatos:
        cn = (c.get("companyName") or "").strip().lower()
        if cn and (cn == alvo or alvo in cn or cn in alvo):
            return c
    for c in contatos:
        full = f"{c.get('firstName') or ''} {c.get('lastName') or ''}".strip().lower()
        if full and (full == alvo or alvo in full or full in alvo):
            return c
    return None


def ja_esta_no_crm(lead):
    tel = primeiro_telefone(lead.get("telefone") or "")
    nome = (lead.get("nome") or "").strip()
    contato = None
    if tel:
        contatos = buscar_contato(tel)
        contato = match_por_telefone(contatos, tel) or match_por_nome(contatos, nome)
    if not contato:
        contatos = buscar_contato(nome)
        contato = match_por_nome(contatos, nome) or match_por_telefone(contatos, tel)
    return contato


def montar_custom_fields(lead):
    cf = []
    for campo, field_id in CAMPOS_MAP.items():
        if campo == "fontes_enriquecimento":
            fontes = lead.get("fontes") or []
            if fontes:
                cf.append({"id": field_id, "value": ", ".join(fontes)})
            continue
        v = lead.get(campo)
        if v:
            cf.append({"id": field_id, "value": str(v)})
    return cf


def criar_contato(lead):
    nome_split = (lead.get("nome") or "").split(" ", 1)
    tel = primeiro_telefone(lead.get("telefone") or "")
    if tel and not tel.startswith("+"):
        tel = "+" + tel if len(tel) >= 11 else tel
    payload = {
        "locationId": LOCATION_ID,
        "firstName": nome_split[0],
        "lastName": nome_split[1] if len(nome_split) > 1 else "",
        "companyName": lead.get("nome"),
        "source": "Enriquecimento",
    }
    if tel:
        payload["phone"] = tel
    if lead.get("email"):
        payload["email"] = lead["email"]
    if lead.get("site"):
        payload["website"] = lead["site"]
    if lead.get("endereco"):
        payload["address1"] = lead["endereco"]

    cf = montar_custom_fields(lead)
    if cf:
        payload["customFields"] = cf

    payload = {k: v for k, v in payload.items() if v}

    r = requests.post(f"{GHL_BASE}/contacts/", headers=HEADERS, json=payload, timeout=20)
    if r.status_code in (200, 201):
        return r.json().get("contact", {}).get("id"), None
    try:
        msg = r.json().get("message") or r.json().get("msg") or str(r.json())[:200]
    except Exception:
        msg = r.text[:200]
    if r.status_code == 400 and "duplicate" in msg.lower():
        return None, "duplicado"
    return None, f"HTTP {r.status_code}: {msg}"


def criar_oportunidade(contact_id, nome):
    payload = {
        "pipelineId": PIPELINE_ID,
        "locationId": LOCATION_ID,
        "name": nome,
        "pipelineStageId": STAGE_ID,
        "status": "open",
        "contactId": contact_id,
        "source": "Enriquecimento",
    }
    r = requests.post(f"{GHL_BASE}/opportunities/", headers=HEADERS, json=payload, timeout=20)
    if r.status_code in (200, 201):
        return True, None
    try:
        msg = r.json().get("message") or str(r.json())[:200]
    except Exception:
        msg = r.text[:120]
    if "duplicate" in msg.lower():
        return True, None
    return False, f"HTTP {r.status_code}: {msg}"


def main():
    leads = json.loads(LEADS_PATH.read_text(encoding="utf-8"))
    print(f"Carregados {len(leads)} leads\n")

    criados = 0
    ja_existiam = 0
    com_erro = 0

    for i, lead in enumerate(leads, 1):
        nome = (lead.get("nome") or "").strip()
        if not nome:
            continue

        existente = ja_esta_no_crm(lead)
        if existente:
            ja_existiam += 1
            print(f"[{i:03d}] {nome} → JÁ EXISTE ({existente.get('id')}), pulando")
            time.sleep(0.3)
            continue

        contact_id, err = criar_contato(lead)
        if not contact_id:
            if err == "duplicado":
                ja_existiam += 1
                print(f"[{i:03d}] {nome} → duplicado no GHL, pulando")
            else:
                com_erro += 1
                print(f"[{i:03d}] {nome} → ERRO ao criar contato: {err}")
            time.sleep(0.5)
            continue

        ok_opp, err_opp = criar_oportunidade(contact_id, nome)
        if ok_opp:
            criados += 1
            print(f"[{i:03d}] {nome} → CRIADO ({contact_id}) com campos customizados")
        else:
            criados += 1
            print(f"[{i:03d}] {nome} → CONTATO criado ({contact_id}) mas opp falhou: {err_opp}")

        time.sleep(0.5)

    print("\n" + "=" * 60)
    print("RESUMO:")
    print(f"  Criados no CRM  : {criados}")
    print(f"  Já existiam     : {ja_existiam}")
    print(f"  Com erro        : {com_erro}")
    print(f"  Total           : {len(leads)}")
    print("=" * 60)


if __name__ == "__main__":
    main()
