#!/usr/bin/env python3
"""
Script para testar monitoramento RSS do ReputacaoDigital
Uso: python3 test-rss.py [keyword]
"""

import urllib.request
import xml.etree.ElementTree as ET
import sys
from datetime import datetime

# Keywords padrão para Banco Master
DEFAULT_KEYWORDS = ["Daniel Vorcaro", "Banco Master"]

# Feeds RSS configurados
FEEDS = {
    "Google News": "https://news.google.com/rss/search?q={keyword}&hl=pt-BR&gl=BR&ceid=BR:pt",
    "InfoMoney": "https://www.infomoney.com.br/feed/",
    "Valor": "https://valor.globo.com/rss/",
    "Exame": "https://exame.com/feed/",
    "G1": "https://g1.globo.com/rss/g1/",
    "Folha": "https://rss.folha.uol.com.br/folha/emcimadahora/rss091.xml",
}

# Palavras para análise de sentimento
NEGATIVE_WORDS = ["fraude", "golpe", "pirâmide", "investigação", "denúncia", "escândalo",
                  "crime", "prisão", "lavagem", "corrupção", "ilegal", "irregularidade",
                  "liquidação", "quebra", "falência", "calote", "prejuízo"]

POSITIVE_WORDS = ["sucesso", "crescimento", "lucro", "prêmio", "inovação", "expansão",
                  "aprovação", "conquista", "reconhecimento", "parceria"]

def fetch_rss(url, keyword=None):
    """Busca e parseia um feed RSS"""
    if keyword:
        url = url.format(keyword=urllib.parse.quote(keyword))

    req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0 ReputacaoDigital/1.0'})

    try:
        with urllib.request.urlopen(req, timeout=15) as response:
            data = response.read()
            root = ET.fromstring(data)
            return root.findall('.//item')
    except Exception as e:
        return []

def analyze_sentiment(text):
    """Analisa sentimento do texto"""
    text_lower = text.lower()

    neg_count = sum(1 for word in NEGATIVE_WORDS if word in text_lower)
    pos_count = sum(1 for word in POSITIVE_WORDS if word in text_lower)

    if neg_count > pos_count:
        return "NEGATIVO", "🔴"
    elif pos_count > neg_count:
        return "POSITIVO", "🟢"
    return "NEUTRO", "⚪"

def search_keyword_in_feed(feed_name, feed_url, keyword):
    """Busca keyword em um feed"""
    items = fetch_rss(feed_url, keyword if "google" in feed_url.lower() else None)
    results = []

    for item in items:
        title = item.find('title').text if item.find('title') is not None else ''
        desc = item.find('description').text if item.find('description') is not None else ''
        link = item.find('link').text if item.find('link') is not None else ''
        source = item.find('source')
        source_name = source.text if source is not None else feed_name

        content = f"{title} {desc}".lower()

        # Para Google News, já vem filtrado
        if "google" in feed_url.lower() or keyword.lower() in content:
            sentiment, icon = analyze_sentiment(f"{title} {desc}")
            results.append({
                'title': title,
                'source': source_name,
                'link': link,
                'sentiment': sentiment,
                'icon': icon
            })

    return results

def main():
    keywords = sys.argv[1:] if len(sys.argv) > 1 else DEFAULT_KEYWORDS

    print("=" * 70)
    print("🔍 REPUTAÇÃO DIGITAL - Teste de Monitoramento RSS")
    print("=" * 70)
    print(f"📅 Data: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"🔑 Keywords: {', '.join(keywords)}")
    print("=" * 70)

    all_results = []

    for keyword in keywords:
        print(f"\n📰 Buscando: '{keyword}'")
        print("-" * 50)

        # Google News (principal)
        results = search_keyword_in_feed("Google News", FEEDS["Google News"], keyword)
        all_results.extend(results)

        for i, r in enumerate(results[:5], 1):
            print(f"{r['icon']} {i}. {r['title'][:60]}...")
            print(f"   └─ {r['source']} [{r['sentiment']}]")

    # Resumo
    print("\n" + "=" * 70)
    print("📊 RESUMO")
    print("=" * 70)

    total = len(all_results)
    negativos = sum(1 for r in all_results if r['sentiment'] == 'NEGATIVO')
    positivos = sum(1 for r in all_results if r['sentiment'] == 'POSITIVO')
    neutros = total - negativos - positivos

    print(f"Total de menções: {total}")
    print(f"🔴 Negativas: {negativos} ({negativos/total*100:.1f}%)" if total > 0 else "")
    print(f"🟢 Positivas: {positivos} ({positivos/total*100:.1f}%)" if total > 0 else "")
    print(f"⚪ Neutras: {neutros} ({neutros/total*100:.1f}%)" if total > 0 else "")

    if negativos > 0:
        print("\n⚠️  ALERTA: Há menções negativas que requerem atenção!")

    print("\n" + "=" * 70)

if __name__ == "__main__":
    main()
