#!/usr/bin/env python3
"""
Importação CSV -> CRM Linkia (GHL) — Pipeline Conafor Smart
Location: PX3 Lab (W7PGxpfbsFaEEUoQOtUb)
Data: 2026-08-27
Usa curl via subprocess para contornar bloqueio de User-Agent do Cloudflare.
"""

import csv
import json
import time
import subprocess
import sys
import os
from datetime import datetime

# ─── CONFIG ────────────────────────────────────────────────────────────────
TOKEN       = "pit-25f78b4f-4cc8-48f2-b8dc-73a98f851eaf"
LOCATION_ID = "W7PGxpfbsFaEEUoQOtUb"
PIPELINE_ID = "6YjM6IvNbe5IWyD9JEqN"   # LEADS QUE VÃO NA PALESTRA CONAFOR
STAGE_ID    = "2ac6d8b7-43cb-49c0-b0e9-8ceecce1c495"  # Novo Lead (position 0)
SOURCE      = "Import CSV Renato 27/08/2026"
CSV_FILE    = "/opt/mia-bot/docs/1787836331382479.csv"
BASE_URL    = "https://services.leadconnectorhq.com"

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

# ─── HELPERS ───────────────────────────────────────────────────────────────

def log(msg):
    ts = datetime.now().strftime("%H:%M:%S")
    line = f"[{ts}] {msg}"
    print(line, flush=True)
    with open(LOG_FILE, "a") as f:
        f.write(line + "\n")


def curl_request(method, path, payload=None, retry=0):
    """Faz request via curl. Retorna (status_code, body_dict)."""
    url = BASE_URL + path
    cmd = [
        "curl", "-s", "-w", "\n__STATUS:%{http_code}",
        "-X", method,
        "-H", f"Authorization: Bearer {TOKEN}",
        "-H", "Version: 2021-07-28",
        "-H", "Content-Type: application/json",
        "-H", "Accept: application/json",
    ]
    if payload:
        cmd += ["-d", json.dumps(payload, ensure_ascii=False)]
    cmd.append(url)

    result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
    raw = result.stdout

    # Extrai status code do sufixo "__STATUS:NNN"
    status = 0
    body_str = raw
    if "\n__STATUS:" in raw:
        parts = raw.rsplit("\n__STATUS:", 1)
        body_str = parts[0].strip()
        try:
            status = int(parts[1].strip())
        except ValueError:
            status = 0

    try:
        body = json.loads(body_str) if body_str else {}
    except Exception:
        body = {"raw": body_str}

    # Rate limit
    if status == 429:
        wait = 2 ** retry
        log(f"  429 rate limit — aguardando {wait}s (retry {retry+1})")
        time.sleep(wait)
        return curl_request(method, path, payload, retry + 1)

    return status, body


def create_contact(first_name, phone):
    """Cria contato. Retorna (contact_id, is_new, error_msg)."""
    payload = {
        "locationId": LOCATION_ID,
        "firstName": first_name,
        "phone": phone,
        "source": SOURCE,
    }
    status, body = curl_request("POST", "/contacts/", payload)

    if status in (200, 201):
        contact_id = (
            body.get("contact", {}).get("id")
            or body.get("id")
        )
        return contact_id, True, None

    # 400 pode ser dedupe — extrai contactId do body
    if status == 400:
        contact_id = (
            body.get("meta", {}).get("contactId")
            or body.get("contactId")
            or body.get("contact", {}).get("id")
        )
        if contact_id:
            return contact_id, False, None
        err = body.get("message") or body.get("error") or str(body)
        return None, False, f"400: {err}"

    err = body.get("message") or body.get("error") or str(body)
    return None, False, f"{status}: {err}"


def create_opportunity(contact_id, first_name):
    """Cria opportunity no pipeline Conafor Smart · stage Novo Lead."""
    payload = {
        "pipelineId": PIPELINE_ID,
        "locationId": LOCATION_ID,
        "name": f"Lead {first_name}",
        "pipelineStageId": STAGE_ID,
        "status": "open",
        "contactId": contact_id,
        "monetaryValue": 0,
        "source": SOURCE,
    }
    status, body = curl_request("POST", "/opportunities/", payload)

    if status in (200, 201):
        opp_id = (
            body.get("opportunity", {}).get("id")
            or body.get("id")
        )
        return opp_id, None

    err = body.get("message") or body.get("error") or str(body)
    return None, f"{status}: {err}"


# ─── MAIN ──────────────────────────────────────────────────────────────────

def main():
    log("=" * 60)
    log("IMPORTAÇÃO CONAFOR SMART — PX3 LAB")
    log(f"Pipeline : {PIPELINE_ID}")
    log(f"Stage    : {STAGE_ID} (Novo Lead)")
    log(f"CSV      : {CSV_FILE}")
    log("=" * 60)

    rows = []
    with open(CSV_FILE, newline="", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        for row in reader:
            rows.append(row)

    total = len(rows)
    log(f"Total de linhas no CSV: {total}")

    contacts_new    = 0
    contacts_reused = 0
    contacts_error  = 0
    opps_created    = 0
    opps_error      = 0
    errors_detail   = []

    start = time.time()

    for i, row in enumerate(rows, 1):
        first_name = row.get("First Name", "").strip()
        phone      = row.get("Phone", "").strip()

        log(f"[{i:03d}/{total}] {first_name} | {phone}")

        if not phone:
            msg = f"Linha {i} — {first_name}: sem telefone"
            log(f"  SKIP: sem telefone")
            errors_detail.append(msg)
            contacts_error += 1
            continue

        # 1. Contato
        contact_id, is_new, err = create_contact(first_name, phone)

        if err:
            msg = f"Linha {i} — {first_name} ({phone}): ERRO contato — {err}"
            log(f"  ERRO contato: {err}")
            errors_detail.append(msg)
            contacts_error += 1
            continue

        if is_new:
            log(f"  Contato CRIADO  : {contact_id}")
            contacts_new += 1
        else:
            log(f"  Contato REUSADO : {contact_id}")
            contacts_reused += 1

        # 2. Opportunity
        opp_id, opp_err = create_opportunity(contact_id, first_name)

        if opp_err:
            msg = f"Linha {i} — {first_name} ({phone}): ERRO opp — {opp_err}"
            log(f"  ERRO opp: {opp_err}")
            errors_detail.append(msg)
            opps_error += 1
        else:
            log(f"  Opportunity     : {opp_id}")
            opps_created += 1

        # Pausa leve entre registros
        time.sleep(0.25)

    elapsed = time.time() - start

    log("")
    log("=" * 60)
    log("RESUMO FINAL")
    log("=" * 60)
    log(f"Total processados        : {total}")
    log(f"Contatos novos criados   : {contacts_new}")
    log(f"Contatos reusados(dedupe): {contacts_reused}")
    log(f"Contatos com erro        : {contacts_error}")
    log(f"Opportunities criadas    : {opps_created}")
    log(f"Opportunities com erro   : {opps_error}")
    log(f"Tempo total              : {elapsed:.1f}s")

    if errors_detail:
        log("")
        log("DETALHES DOS ERROS:")
        for e in errors_detail:
            log(f"  - {e}")

    log(f"\nLog salvo em: {LOG_FILE}")

    result = {
        "total": total,
        "contacts_new": contacts_new,
        "contacts_reused": contacts_reused,
        "contacts_error": contacts_error,
        "opps_created": opps_created,
        "opps_error": opps_error,
        "elapsed_s": round(elapsed, 1),
        "errors": errors_detail,
        "log_file": LOG_FILE,
    }

    with open(LOG_FILE, "a") as f:
        f.write("\nJSON_RESULT=" + json.dumps(result, ensure_ascii=False) + "\n")

    return result


if __name__ == "__main__":
    result = main()
    print("\nRESULT_JSON=" + json.dumps(result, ensure_ascii=False))
