#!/usr/bin/env python3
"""
Testa o webhook TORQ SDR Bruno localmente.

Roda 4 cenarios simulando payloads do GHL:
  1. Primeira mensagem do lead (fase A — Acolher)
  2. Qualificacao (fase L — dados)
  3. Objecao (marca chinesa)
  4. Amarracao (test drive)

NAO envia mensagem real pro WhatsApp — o webhook faz isso, mas o teste apenas
valida que o endpoint responde 200 e que Bruno gera texto coerente + meta.

Uso:
    python3 tests/test_webhook.py
    (webhook precisa estar rodando em http://localhost:8920)
"""

from __future__ import annotations

import json
import sys
import time
import uuid

import requests

WEBHOOK_URL = "http://localhost:8940/webhook"
HEALTH_URL = "http://localhost:8940/health"

# Contato fake pra teste (nao vai realmente responder)
TEST_CONTACT_ID = "TEST-CONTACT-" + uuid.uuid4().hex[:8]
TEST_CONVERSATION_ID = "TEST-CONV-" + uuid.uuid4().hex[:8]


def check_health() -> bool:
    try:
        r = requests.get(HEALTH_URL, timeout=5)
        if r.ok:
            print("[health]", json.dumps(r.json(), ensure_ascii=False, indent=2))
            return True
        print("[health] FALHOU status", r.status_code)
    except Exception as e:
        print("[health] erro:", e)
    return False


def send_msg(mensagem: str, first_name: str = "Marcos") -> dict:
    payload = {
        "id": f"MSG-{uuid.uuid4().hex[:12]}",
        "contactId": TEST_CONTACT_ID,
        "conversationId": TEST_CONVERSATION_ID,
        "body": mensagem,
        "type": "WhatsApp",
        "direction": "inbound",
        "firstName": first_name,
        "phone": "+5531999999999",
    }
    print(f"\n>>> Lead: {mensagem}")
    r = requests.post(WEBHOOK_URL, json=payload, timeout=10)
    print(f"    HTTP {r.status_code} {r.text[:200]}")
    return r.json() if r.ok else {}


def main() -> int:
    print("=" * 70)
    print("TESTE WEBHOOK TORQ SDR BRUNO")
    print(f"contact_id: {TEST_CONTACT_ID}")
    print("=" * 70)

    if not check_health():
        print("SERVICE NAO ESTA RODANDO — sobe com: sudo systemctl start torq-sdr.service")
        return 1

    # Cenario 1: primeira msg
    send_msg("oi vi anuncio da bike de vcs, queria conhecer")
    print("[aguardando debounce + resposta Bruno...]")
    time.sleep(20)

    # Cenario 2: qualificacao
    send_msg("Marcos. Sou de BH, moro no Buritis. Trabalho no Barreiro, uns 12km")
    time.sleep(20)

    # Cenario 3: objecao
    send_msg("mas nunca ouvi falar dessa marca, e chinesa?")
    time.sleep(20)

    # Cenario 4: agenda visita
    send_msg("sabado 10h vou passar la sim")
    time.sleep(20)

    print("\n" + "=" * 70)
    print("Teste enviado. Confira /opt/mia/logs/sdr_bruno.log:")
    print("  tail -f /opt/mia/logs/sdr_bruno.log")
    print("Bruno deve ter respondido, atualizado custom fields e movido stage.")
    print("=" * 70)
    return 0


if __name__ == "__main__":
    sys.exit(main())
