#!/usr/bin/env python3
"""
Generate suggested responses for hot leads using Claude API
"""

import json
import urllib.request
from pathlib import Path

API_URL = "https://api.anthropic.com/v1/messages"
MODEL = "claude-sonnet-4-20250514"

def load_api_key() -> str:
    key_file = Path.home() / ".anthropic" / "api_key"
    if key_file.exists():
        return key_file.read_text().strip()
    return ""

def call_claude(prompt: str, api_key: str) -> str:
    headers = {
        "Content-Type": "application/json",
        "x-api-key": api_key,
        "anthropic-version": "2023-06-01"
    }

    data = json.dumps({
        "model": MODEL,
        "max_tokens": 1024,
        "messages": [{"role": "user", "content": prompt}]
    }).encode()

    req = urllib.request.Request(API_URL, data=data, headers=headers, method="POST")

    try:
        with urllib.request.urlopen(req, timeout=60) as response:
            result = json.loads(response.read().decode())
            return result["content"][0]["text"]
    except Exception as e:
        return f"Erro: {e}"

def main():
    api_key = load_api_key()
    if not api_key:
        print("API key não encontrada!")
        return

    # Load analyzed data
    data_file = Path.home() / "Documents" / "instagram_dm_leads_analyzed.json"
    with open(data_file) as f:
        data = json.load(f)

    conversations = data.get("conversations", [])

    # Filter hot leads (score >= 60) and warm leads (40-59)
    hot_leads = [c for c in conversations if c.get("analysis", {}).get("leadScore", 0) >= 60]
    warm_leads = [c for c in conversations if 40 <= c.get("analysis", {}).get("leadScore", 0) < 60]
    all_leads = hot_leads + warm_leads

    print("=" * 70)
    print(f"RESPOSTAS SUGERIDAS - {len(hot_leads)} QUENTES + {len(warm_leads)} MORNOS")
    print("=" * 70)

    responses = []

    for lead in all_leads:
        username = lead.get("participantUsername", "")
        preview = lead.get("lastMessagePreview", "")
        analysis = lead.get("analysis", {})
        score = analysis.get("leadScore", 0)
        intent = analysis.get("intent", "")
        summary = analysis.get("summary", "")

        print(f"\n{'─' * 70}")
        print(f"📱 @{username} (Score: {score})")
        print(f"   Última msg: {preview[:60]}...")
        print(f"   Contexto: {summary}")
        print(f"\n   Gerando resposta...")

        prompt = f"""Gere uma resposta de DM do Instagram para este lead.

CONTEXTO:
- Username: @{username}
- Última mensagem: "{preview}"
- Intenção detectada: {intent}
- Resumo da conversa: {summary}

INSTRUÇÕES:
1. A resposta deve ser em português brasileiro
2. Tom: profissional mas amigável, direto ao ponto
3. Máximo 3-4 linhas (DM curta)
4. Se for sobre e-sim/dados: oferecer ajuda para verificar compatibilidade e mostrar planos
5. Se respondeu a anúncio: agradecer interesse e perguntar como pode ajudar
6. Se pediu suporte: demonstrar disponibilidade
7. Incluir call-to-action claro (pergunta ou próximo passo)

Retorne APENAS o texto da resposta, sem aspas ou explicações."""

        response = call_claude(prompt, api_key)

        print(f"\n   💬 RESPOSTA SUGERIDA:")
        print(f"   {'-' * 50}")
        for line in response.split('\n'):
            print(f"   {line}")
        print(f"   {'-' * 50}")

        responses.append({
            "username": username,
            "leadScore": score,
            "intent": intent,
            "lastMessage": preview,
            "suggestedResponse": response
        })

    # Save responses
    output_file = Path.home() / "Documents" / "instagram_dm_responses.json"
    with open(output_file, "w") as f:
        json.dump({"responses": responses}, f, indent=2, ensure_ascii=False)

    print(f"\n{'=' * 70}")
    print(f"✅ {len(responses)} respostas geradas!")
    print(f"📄 Salvo em: {output_file}")
    print("=" * 70)

    # Also create a quick copy-paste format
    txt_file = Path.home() / "Documents" / "instagram_dm_responses.txt"
    with open(txt_file, "w") as f:
        f.write("RESPOSTAS SUGERIDAS - LEADS QUENTES\n")
        f.write("=" * 50 + "\n\n")
        for r in responses:
            f.write(f"@{r['username']} (Score: {r['leadScore']})\n")
            f.write(f"Contexto: {r['lastMessage'][:50]}...\n")
            f.write(f"\nRESPOSTA:\n{r['suggestedResponse']}\n")
            f.write("\n" + "-" * 50 + "\n\n")

    print(f"📝 Texto para copiar: {txt_file}")

if __name__ == "__main__":
    main()
