"""
chatwoot_sender.py — Audit trail de magic links via Chatwoot.

Cria conversation no Chatwoot pra cada magic link enviado.
Stack stdlib-only (urllib).

Variáveis de ambiente:
  CHATWOOT_BASE_URL          → ex: https://chat.sixaesthetic.com.br
  CHATWOOT_API_ACCESS_TOKEN  → User access token do Dalton (Profile → API Tokens)
  CHATWOOT_ACCOUNT_ID        → default 4 (Executivo Privado)
  CHATWOOT_INBOX_ID          → default 7 (Dalton-Pessoal)
  CHATWOOT_AUDIT_ENABLED     → "true" pra ativar (default false)

Audit flow:
  1. Cria/encontra contato pelo email
  2. Cria conversation na inbox Dalton-Pessoal
  3. Envia mensagem com magic link URL como Activity/Note

Não bloqueia envio principal (WhatsApp Evolution) — é apenas paralelo pra audit.
"""

from __future__ import annotations

import json
import os
import urllib.error
import urllib.request
from typing import Optional, Tuple

CHATWOOT_BASE_URL = os.environ.get("CHATWOOT_BASE_URL", "https://chat.sixaesthetic.com.br").rstrip("/")
CHATWOOT_API_TOKEN = os.environ.get("CHATWOOT_API_ACCESS_TOKEN", "")
CHATWOOT_ACCOUNT_ID = int(os.environ.get("CHATWOOT_ACCOUNT_ID", "4"))
CHATWOOT_INBOX_ID = int(os.environ.get("CHATWOOT_INBOX_ID", "7"))
CHATWOOT_AUDIT_ENABLED = os.environ.get("CHATWOOT_AUDIT_ENABLED", "false").lower() in ("true", "1", "yes")
CHATWOOT_TIMEOUT_SEC = int(os.environ.get("CHATWOOT_TIMEOUT_SEC", "10"))


def is_configured() -> bool:
    return CHATWOOT_AUDIT_ENABLED and bool(CHATWOOT_BASE_URL and CHATWOOT_API_TOKEN)


def _request(method: str, path: str, payload: Optional[dict] = None) -> Tuple[int, dict]:
    url = f"{CHATWOOT_BASE_URL}{path}"
    data = json.dumps(payload).encode("utf-8") if payload else None
    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "api_access_token": CHATWOOT_API_TOKEN,
    }
    req = urllib.request.Request(url, data=data, headers=headers, method=method)
    try:
        with urllib.request.urlopen(req, timeout=CHATWOOT_TIMEOUT_SEC) as resp:
            body = resp.read().decode("utf-8")
            return resp.status, (json.loads(body) if body else {})
    except urllib.error.HTTPError as e:
        try:
            body = e.read().decode("utf-8", errors="ignore")[:300]
        except Exception:
            body = ""
        return e.code, {"error": body}
    except urllib.error.URLError as e:
        return 0, {"error": f"URLError: {e.reason}"}
    except Exception as e:
        return 0, {"error": f"{type(e).__name__}: {e}"}


def _find_or_create_contact(email: str, name: Optional[str] = None) -> Optional[int]:
    """Procura contato por email; cria se não existir. Retorna contact_id ou None."""
    # Search
    code, data = _request("GET", f"/api/v1/accounts/{CHATWOOT_ACCOUNT_ID}/contacts/search?q={urllib.parse.quote(email)}")
    if code == 200:
        payload = data.get("payload", [])
        if payload:
            return payload[0].get("id")

    # Create
    create_payload = {
        "inbox_id": CHATWOOT_INBOX_ID,
        "name": name or email.split("@")[0],
        "email": email,
        "identifier": email,
    }
    code, data = _request("POST", f"/api/v1/accounts/{CHATWOOT_ACCOUNT_ID}/contacts", create_payload)
    if code in (200, 201):
        return data.get("payload", {}).get("contact", {}).get("id") or data.get("id")
    return None


def audit_magic_link(
    email: str,
    magic_link_url: str,
    channel: str = "whatsapp",
    target: str = "",
    success: bool = True,
) -> Tuple[bool, str]:
    """
    Cria conversation no Chatwoot inbox Dalton-Pessoal com info do magic link enviado.

    Retorna (ok, conversation_id_or_error).
    """
    if not is_configured():
        return False, "chatwoot-not-configured"

    import urllib.parse  # late import pra usar quote

    # 1. Find/create contact
    contact_id = _find_or_create_contact(email)
    if not contact_id:
        return False, "contact-not-created"

    # 2. Create conversation
    status_emoji = "✅" if success else "❌"
    msg = (
        f"{status_emoji} *Magic link enviado*\n\n"
        f"📧 Destinatário: {email}\n"
        f"📱 Canal: {channel} → {target}\n"
        f"🔗 Link: {magic_link_url}\n\n"
        f"_Audit automático do Six Hype. Expira em 15min._"
    )

    conv_payload = {
        "source_id": email,
        "inbox_id": CHATWOOT_INBOX_ID,
        "contact_id": contact_id,
        "additional_attributes": {
            "audit_type": "magic_link_sent",
            "channel": channel,
            "target": target,
            "success": success,
        },
        "message": {"content": msg, "message_type": "outgoing"},
    }
    code, data = _request("POST", f"/api/v1/accounts/{CHATWOOT_ACCOUNT_ID}/conversations", conv_payload)

    if code in (200, 201):
        conv_id = data.get("id") or data.get("payload", {}).get("id", "?")
        return True, f"conversation-{conv_id}"
    return False, f"HTTP {code}: {str(data)[:150]}"


if __name__ == "__main__":
    # Smoke test
    print(f"is_configured: {is_configured()}")
    print(f"CHATWOOT_BASE_URL: {CHATWOOT_BASE_URL}")
    print(f"CHATWOOT_ACCOUNT_ID: {CHATWOOT_ACCOUNT_ID}")
    print(f"CHATWOOT_INBOX_ID: {CHATWOOT_INBOX_ID}")
    print(f"CHATWOOT_API_TOKEN length: {len(CHATWOOT_API_TOKEN)}")
    print()
    if is_configured():
        ok, info = audit_magic_link(
            "teste@example.com",
            "https://hype.sixaesthetic.com.br/?token=test",
            channel="whatsapp",
            target="+5511947452497",
            success=True,
        )
        print(f"Audit test: ok={ok}, info={info}")
    else:
        print("Setup CHATWOOT_API_ACCESS_TOKEN + CHATWOOT_AUDIT_ENABLED=true pra testar.")
