import requests
import json
import os
import xml.etree.ElementTree as ET

TELEGRAM_TOKEN = "8816727123:AAFvd_1oh1ZAQq69kz1mvD1QCWbZyMkaRKw"
CHAT_ID = "1640434336"
STATE_FILE = "/home/ubuntu/GhostAgency/social_state.json"

# Subreddit in cui cercare (aggiungiamo italy, informatica, e parma se esiste)
RSS_FEEDS = [
    "https://www.reddit.com/r/ItalyInformatica/new/.rss",
    "https://www.reddit.com/r/italy/new/.rss",
    "https://www.reddit.com/r/Avvocati/new/.rss", # Ottimo per trovare professionisti disperati
]

KEYWORDS = ["sito web", "sito lento", "cerco programmatore", "informatico", "agenzia web", "ecommerce", "software", "bug"]

def send_telegram(text, url):
    msg = f"🔥 *LEAD CALDO INTERCETTATO* 🔥\n\nQualcuno ha appena scritto un post con una parola chiave interessante!\n\nLink: {url}"
    api_url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
    requests.post(api_url, json={"chat_id": CHAT_ID, "text": msg, "parse_mode": "Markdown"})

def scan_socials():
    if os.path.exists(STATE_FILE):
        with open(STATE_FILE, "r") as f:
            seen_posts = json.load(f)
    else:
        seen_posts = []

    headers = {'User-Agent': 'Mozilla/5.0 (GhostAgency Radar Bot 1.0)'}

    for feed in RSS_FEEDS:
        try:
            response = requests.get(feed, headers=headers, timeout=10)
            root = ET.fromstring(response.content)
            
            # Formato Atom RSS XML
            for entry in root.findall('{http://www.w3.org/2005/Atom}entry'):
                post_id = entry.find('{http://www.w3.org/2005/Atom}id').text
                title = entry.find('{http://www.w3.org/2005/Atom}title').text
                link = entry.find('{http://www.w3.org/2005/Atom}link').attrib['href']
                
                if post_id in seen_posts:
                    continue
                    
                # Controllo Keywords nel titolo (case insensitive)
                title_lower = title.lower()
                for kw in KEYWORDS:
                    if kw in title_lower:
                        send_telegram(title, link)
                        break # Evita di mandare due notifiche per lo stesso post
                
                seen_posts.append(post_id)
                
        except Exception as e:
            print(f"Errore RSS {feed}: {e}")

    # Mantieni solo gli ultimi 500 post per non far esplodere il file
    if len(seen_posts) > 500:
        seen_posts = seen_posts[-500:]

    with open(STATE_FILE, "w") as f:
        json.dump(seen_posts, f)

if __name__ == "__main__":
    scan_socials()
