#!/usr/bin/env python3
"""
Cria oportunidades no pipeline LANÇAMENTO 2.0 - 07.10 para todos os elegíveis.
Faz dedupe: pula se já existe oportunidade nesse pipeline.
"""

import requests
import time
import json
import sys

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

PIPELINE_ID = "jGfUw3EOgLZ8KNCIEpAV"        # LANÇAMENTO 2.0 - 07.10
STAGE_ID    = "19ff2b37-5269-4204-b23d-95dd133c9a52"  # Novo Lead

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

BASE_DIR = '/opt/mia/workspace/clientes/px3lab/mapeamento_leads_lancamento_1007'

# Carregar elegíveis
with open(f'{BASE_DIR}/elegiveis.json') as f:
    elegiveis = json.load(f)

print(f"Elegíveis carregados: {len(elegiveis)}")

# Buscar oportunidades existentes nesse pipeline (para dedupe)
def fetch_existing_opportunities():
    """Busca todas as oportunidades já existentes no pipeline do lançamento"""
    existing_contact_ids = set()
    url = f"{BASE_URL}/opportunities/search?location_id={LOCATION_ID}&pipeline_id={PIPELINE_ID}&limit=100"
    page = 0
    
    while url:
        page += 1
        resp = requests.get(url, headers=HEADERS)
        
        if resp.status_code != 200:
            print(f"  ERRO buscando opps página {page}: {resp.status_code} {resp.text[:200]}")
            break
        
        data = resp.json()
        opps = data.get('opportunities', [])
        
        for opp in opps:
            cid = opp.get('contact', {}).get('id') or opp.get('contactId')
            if cid:
                existing_contact_ids.add(cid)
        
        meta = data.get('meta', {})
        total = meta.get('total', 0)
        if page == 1:
            print(f"  Total oportunidades existentes no pipeline: {total}")
        
        next_page = meta.get('nextPage')
        if next_page and len(existing_contact_ids) < total:
            start_after = meta.get('startAfterId')
            start_after_ts = meta.get('startAfter')
            if start_after and start_after_ts:
                url = f"{BASE_URL}/opportunities/search?location_id={LOCATION_ID}&pipeline_id={PIPELINE_ID}&limit=100&startAfter={start_after_ts}&startAfterId={start_after}"
            else:
                url = meta.get('nextPageUrl')
        else:
            url = None
        
        if url:
            time.sleep(0.15)
    
    print(f"  Contact IDs com oportunidade existente: {len(existing_contact_ids)}")
    return existing_contact_ids

print("\n=== VERIFICANDO OPORTUNIDADES EXISTENTES ===")
existing = fetch_existing_opportunities()

# Criar oportunidades
criadas = []
puladas_dedupe = []
falhas = []

total = len(elegiveis)
print(f"\n=== CRIANDO OPORTUNIDADES ===")
print(f"Total a processar: {total}")
print(f"Já existentes no pipeline (dedupe): {len(existing)}")

for i, contact in enumerate(elegiveis, 1):
    cid = contact.get('id')
    first = contact.get('firstName', '') or ''
    last = contact.get('lastName', '') or ''
    name = f"{first} {last}".strip() or 'Sem nome'
    
    # Dedupe
    if cid in existing:
        puladas_dedupe.append({'id': cid, 'name': name})
        continue
    
    # Montar payload
    opp_name = f"Lançamento 2.0 - {name}"
    
    payload = {
        "pipelineId": PIPELINE_ID,
        "pipelineStageId": STAGE_ID,
        "locationId": LOCATION_ID,
        "contactId": cid,
        "name": opp_name,
        "status": "open",
        "monetaryValue": 0
    }
    
    resp = requests.post(
        f"{BASE_URL}/opportunities/",
        headers=HEADERS,
        json=payload
    )
    
    if resp.status_code in (200, 201):
        opp_id = resp.json().get('opportunity', {}).get('id', 'N/A')
        criadas.append({'id': cid, 'name': name, 'opp_id': opp_id})
    elif resp.status_code == 400:
        # Gotcha: 400 pode indicar que o contactId já foi usado (dedupe)
        err_body = resp.json()
        err_msg = str(err_body)
        if 'already' in err_msg.lower() or 'exist' in err_msg.lower() or 'duplicate' in err_msg.lower():
            puladas_dedupe.append({'id': cid, 'name': name, 'note': '400-dedupe'})
        else:
            falhas.append({'id': cid, 'name': name, 'status': resp.status_code, 'err': err_msg[:200]})
    else:
        falhas.append({'id': cid, 'name': name, 'status': resp.status_code, 'err': resp.text[:200]})
    
    # Checkpoint a cada 100
    if i % 100 == 0:
        print(f"  Checkpoint {i}/{total}: criadas={len(criadas)}, puladas={len(puladas_dedupe)}, falhas={len(falhas)}")
    
    # Rate limit: ~5-7 req/s
    time.sleep(0.15)

# Resultado final
print(f"\n=== RESULTADO FINAL ===")
print(f"Total elegíveis processados: {len(elegiveis)}")
print(f"Oportunidades CRIADAS: {len(criadas)}")
print(f"Puladas por dedupe: {len(puladas_dedupe)}")
print(f"FALHAS: {len(falhas)}")

# Salvar logs
with open(f'{BASE_DIR}/resultado_criacao.json', 'w') as f:
    json.dump({
        'criadas': criadas,
        'puladas_dedupe': puladas_dedupe,
        'falhas': falhas
    }, f, ensure_ascii=False, indent=2)

if falhas:
    print(f"\nDetalhes das falhas (primeiras 10):")
    for f_item in falhas[:10]:
        print(f"  {f_item}")

print(f"\nLog completo salvo em resultado_criacao.json")

