#!/usr/bin/env python3
"""
Atualiza o campo 'Status Tarefa' nas oportunidades do pipeline PX3.
🟢 = tem tarefa futura (em dia)
🟡 = sem tarefa cadastrada
🔴 = tem tarefa vencida (atrasada)
Roda via cron a cada 30 minutos.
"""
import requests
from datetime import datetime, timezone
import json, os, sys

GHL_TOKEN = "pit-25f78b4f-4cc8-48f2-b8dc-73a98f851eaf"
GHL_LOCATION = "W7PGxpfbsFaEEUoQOtUb"
GHL_BASE = "https://services.leadconnectorhq.com"
HEADERS = {"Authorization": f"Bearer {GHL_TOKEN}", "Version": "2021-07-28", "Content-Type": "application/json"}

# ID do campo customizado criado via API em 2026-06-23
CAMPO_STATUS_ID = "cvrJJ7rlAuIGgCL42NEH"

def buscar_oportunidades():
    """Busca todas as oportunidades abertas da location usando paginacao cursor-based."""
    opps = []
    params = {"location_id": GHL_LOCATION, "status": "open", "limit": 100}
    while True:
        r = requests.get(f"{GHL_BASE}/opportunities/search",
                         headers=HEADERS,
                         params=params,
                         timeout=15)
        if r.status_code != 200:
            print(f"Erro ao buscar oportunidades: {r.status_code} {r.text[:200]}")
            break
        data = r.json()
        batch = data.get("opportunities") or []
        opps.extend(batch)
        meta = data.get("meta", {})
        start_after = meta.get("startAfter")
        start_after_id = meta.get("startAfterId")
        if not start_after or not start_after_id or len(batch) < 100:
            break
        params = {
            "location_id": GHL_LOCATION,
            "status": "open",
            "limit": 100,
            "startAfter": start_after,
            "startAfterId": start_after_id
        }
    return opps

def buscar_tarefas_contato(contact_id):
    """Busca tarefas do contato."""
    r = requests.get(f"{GHL_BASE}/contacts/{contact_id}/tasks",
                     headers=HEADERS, timeout=10)
    if r.status_code != 200:
        return []
    return r.json().get("tasks") or []

def calcular_farol(tarefas):
    """Retorna 🟢, 🟡 ou 🔴 baseado nas tarefas."""
    pendentes = [t for t in tarefas if not t.get("completed")]
    if not pendentes:
        return "🟡"  # sem tarefa
    agora = datetime.now(timezone.utc)
    for t in pendentes:
        due = t.get("dueDate")
        if due:
            try:
                # dueDate pode vir como timestamp ms ou string ISO
                if isinstance(due, (int, float)):
                    dt = datetime.fromtimestamp(due / 1000, tz=timezone.utc)
                else:
                    dt = datetime.fromisoformat(due.replace("Z", "+00:00"))
                if dt < agora:
                    return "🔴"  # atrasada
            except Exception:
                pass
    return "🟢"  # em dia

def atualizar_oportunidade(opp_id, farol):
    """Atualiza o campo Status Tarefa da oportunidade."""
    body = {"customFields": [{"id": CAMPO_STATUS_ID, "value": farol}]}
    r = requests.put(f"{GHL_BASE}/opportunities/{opp_id}",
                     headers=HEADERS, json=body, timeout=10)
    return r.status_code in (200, 201)

def main():
    print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] Iniciando atualização de faróis...")
    opps = buscar_oportunidades()
    print(f"  {len(opps)} oportunidades encontradas")
    ok = err = 0
    for opp in opps:
        opp_id = opp.get("id")
        contact_id = opp.get("contactId") or (opp.get("contact") or {}).get("id")
        if not opp_id or not contact_id:
            continue
        tarefas = buscar_tarefas_contato(contact_id)
        farol = calcular_farol(tarefas)
        if atualizar_oportunidade(opp_id, farol):
            ok += 1
        else:
            err += 1
    print(f"  Atualizado: {ok} | Erro: {err}")

if __name__ == "__main__":
    main()
