#!/usr/bin/env python3
"""
FIX: Move 120 opportunities do pipeline ERRADO para o CONAFOR SMART
Pipeline errado : 6YjM6IvNbe5IWyD9JEqN (LEADS QUE VAO NA PALESTRA CONAFOR)
Pipeline correto: 3H0v6vq6oa7oOST4mKTV (CONAFOR SMART)
Stage correto   : e6b37871-95a9-49ee-95db-027c9d301454 (Novo Lead, position 0)
"""

import json
import time
import re
import requests
from datetime import datetime

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

PIPELINE_CORRETO = "3H0v6vq6oa7oOST4mKTV"
STAGE_NOVO_LEAD  = "e6b37871-95a9-49ee-95db-027c9d301454"

LOG_PATH = f"/opt/mia/workspace/clientes/px3lab/imports/conafor_smart_FIX_{datetime.now().strftime('%Y%m%d_%H%M')}.log"

# -------------------------------------------------------
# Extrair opportunity_id e contact_id do log anterior
# -------------------------------------------------------
LOG_SRC = "/opt/mia/workspace/clientes/px3lab/imports/conafor_smart_20260827_1315.log"

opp_contact_pairs = []  # list of (opp_id, contact_id, name)

with open(LOG_SRC) as f:
    lines = f.readlines()

# Parsear bloco a bloco: cada lead tem 3 linhas relevantes
# [NNN/120] Nome | telefone
# Contato REUSADO/CRIADO : <contact_id>
# Opportunity     : <opp_id>
i = 0
while i < len(lines):
    m_lead = re.search(r'\[(\d+)/120\] (.+?) \|', lines[i])
    if m_lead:
        name = m_lead.group(2).strip()
        contact_id = None
        opp_id = None
        # look ahead up to 4 lines
        for j in range(i+1, min(i+5, len(lines))):
            mc = re.search(r'Contato (?:REUSADO|CRIADO)\s*:\s*(\S+)', lines[j])
            if mc:
                contact_id = mc.group(1)
            mo = re.search(r'Opportunity\s*:\s*(\S+)', lines[j])
            if mo:
                opp_id = mo.group(1)
        if contact_id and opp_id:
            opp_contact_pairs.append((opp_id, contact_id, name))
    i += 1

print(f"Pares encontrados no log: {len(opp_contact_pairs)}")

# -------------------------------------------------------
# Helpers
# -------------------------------------------------------

def api_call(method, path, **kwargs):
    """Faz chamada à API com backoff em caso de 429."""
    url = BASE_URL + path
    delay = 1
    for attempt in range(5):
        resp = method(url, headers=HEADERS, **kwargs)
        # sempre consumir body
        try:
            body = resp.json()
        except Exception:
            body = {}
        if resp.status_code == 429:
            wait = delay * (2 ** attempt)
            print(f"  429 rate-limit, aguardando {wait}s...")
            time.sleep(wait)
            continue
        return resp.status_code, body
    return resp.status_code, body

# -------------------------------------------------------
# Executar
# -------------------------------------------------------

log_lines = []

def log(msg):
    ts = datetime.now().strftime("%H:%M:%S")
    line = f"[{ts}] {msg}"
    print(line)
    log_lines.append(line)

log("=" * 60)
log("FIX CONAFOR SMART — DELETAR PIPELINE ERRADO + RECRIAR")
log(f"Pipeline correto : {PIPELINE_CORRETO}")
log(f"Stage Novo Lead  : {STAGE_NOVO_LEAD}")
log(f"Total a processar: {len(opp_contact_pairs)}")
log("=" * 60)

deleted_ok   = []
deleted_fail = []
created_ok   = []
created_fail = []

for idx, (opp_id, contact_id, name) in enumerate(opp_contact_pairs, 1):
    label = f"[{idx:03d}/{len(opp_contact_pairs)}] {name}"

    # --- DELETAR ---
    status, body = api_call(requests.delete, f"/opportunities/{opp_id}")
    if status in (200, 204):
        log(f"{label} | DELETE {opp_id} OK")
        deleted_ok.append(opp_id)
    else:
        log(f"{label} | DELETE {opp_id} FALHOU ({status}) - {body}")
        deleted_fail.append((opp_id, status, body))

    # Pequena pausa para não estourar rate limit
    time.sleep(0.3)

    # --- RECRIAR ---
    payload = {
        "pipelineId":  PIPELINE_CORRETO,
        "locationId":  LOCATION_ID,
        "contactId":   contact_id,
        "pipelineStageId": STAGE_NOVO_LEAD,
        "status":      "open",
        "name":        f"{name} - CONAFOR SMART",
        "source":      "Import CSV Renato 27/08/2026",
    }
    status2, body2 = api_call(requests.post, "/opportunities/", json=payload)
    if status2 in (200, 201):
        new_opp_id = body2.get("opportunity", {}).get("id", "?")
        log(f"{label} | CREATE contact={contact_id} -> new_opp={new_opp_id} OK")
        created_ok.append({"old_opp": opp_id, "new_opp": new_opp_id, "contact": contact_id, "name": name})
    else:
        log(f"{label} | CREATE FALHOU ({status2}) - {body2}")
        created_fail.append({"opp_id": opp_id, "contact_id": contact_id, "status": status2, "body": body2})

    time.sleep(0.4)

log("")
log("=" * 60)
log("RESUMO FASE 1 (delete + create)")
log("=" * 60)
log(f"Deletados OK    : {len(deleted_ok)}")
log(f"Deletados FAIL  : {len(deleted_fail)}")
log(f"Criados OK      : {len(created_ok)}")
log(f"Criados FAIL    : {len(created_fail)}")
if deleted_fail:
    log(f"FALHAS DELETE: {deleted_fail}")
if created_fail:
    log(f"FALHAS CREATE: {created_fail}")

# -------------------------------------------------------
# Validar: listar opportunities do pipeline CONAFOR SMART
# -------------------------------------------------------
log("")
log("Aguardando 60s para indexação antes de validar...")
time.sleep(60)

log("Validando pipeline CONAFOR SMART — Novo Lead...")
status_v, body_v = api_call(
    requests.get,
    f"/opportunities/search?location_id={LOCATION_ID}&pipeline_id={PIPELINE_CORRETO}&pipeline_stage_id={STAGE_NOVO_LEAD}&limit=100"
)
total_encontrado = body_v.get("meta", {}).get("total", "?")
log(f"Total no CONAFOR SMART / Novo Lead (pag 1, limit 100): {total_encontrado}")

# segunda página se total > 100
if isinstance(total_encontrado, int) and total_encontrado >= 100:
    status_v2, body_v2 = api_call(
        requests.get,
        f"/opportunities/search?location_id={LOCATION_ID}&pipeline_id={PIPELINE_CORRETO}&pipeline_stage_id={STAGE_NOVO_LEAD}&limit=100&startAfter=100"
    )
    total_p2 = len(body_v2.get("opportunities", []))
    log(f"Página 2 retornou mais {total_p2} registros")

log("")
log("=" * 60)
log("RESULTADO FINAL")
log(f"pipeline_id  CONAFOR SMART : {PIPELINE_CORRETO}")
log(f"stage_id     Novo Lead     : {STAGE_NOVO_LEAD}")
log(f"Deletados do pipeline errado : {len(deleted_ok)}")
log(f"Criados no pipeline correto  : {len(created_ok)}")
log(f"Total validado na API        : {total_encontrado}")
log("=" * 60)

# Salvar log
with open(LOG_PATH, "w") as f:
    f.write("\n".join(log_lines))

# Resultado JSON para Mia
result = {
    "pipeline_id_correto": PIPELINE_CORRETO,
    "stage_id_novo_lead": STAGE_NOVO_LEAD,
    "total_deletado_pipeline_errado": len(deleted_ok),
    "total_criado_pipeline_correto": len(created_ok),
    "erros_delete": len(deleted_fail),
    "erros_create": len(created_fail),
    "total_validado_api": total_encontrado,
    "log": LOG_PATH,
    "fail_details_delete": deleted_fail,
    "fail_details_create": created_fail,
}
print("\nJSON_RESULT=" + json.dumps(result))
