#!/usr/bin/env python3
"""
Ghost Agency Social Radar - Fixed Reddit RSS + HackerNews + Lobsters
Monitora fonti aperte per lead caldi (persone che chiedono dev/web/siti).
"""
import os
import json
import requests
import xml.etree.ElementTree as ET
from pathlib import Path

TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN", "8816727123:AAFvd_1oh1ZAQq69kz1mvD1QCWbZyMkaRKw")
CHAT_ID = os.getenv("CHAT_ID", "1640434336")
STATE_FILE = Path("/home/ubuntu/GhostAgency/social_state.json")

# Fonti RSS affidabili
RSS_FEEDS = [
    # Reddit - usa old.reddit.com che è più permissivo
    "https://old.reddit.com/r/ItalyInformatica/new/.rss",
    "https://old.reddit.com/r/italy/new/.rss",
    "https://old.reddit.com/r/Avvocati/new/.rss",
    "https://old.reddit.com/r/imprenditoria/new/.rss",
    "https://old.reddit.com/r/freelance/new/.rss",
    "https://old.reddit.com/r/webdev/new/.rss",
    "https://old.reddit.com/r/italianprogrammers/new/.rss",
    
    # Hacker News - chi cerca dev / "Ask HN: Who is hiring"
    "https://hnrss.org/newest?q=sito+web+OR+sito+lento+OR+cerco+programmatore+OR+freelance+OR+webdev+OR+wordpress+OR+ecommerce",
    
    # Lobste.rs - tech community
    "https://lobste.rs/newest.rss",
]

KEYWORDS = [
    "sito web", "sito lento", "cerco programmatore", "informatico", 
    "agenzia web", "ecommerce", "software", "bug", "freelance",
    "sviluppatore", "web developer", "wordpress", "prestashop",
    "shopify", "woocommerce", "landing page", "sito aziendale",
    "rifare il sito", "nuovo sito", "chi fa siti", "preventivo sito"
]

HEADERS = {
    "User-Agent": "Mozilla/5.0 (GhostAgency SocialRadar/2.0; +https://svoraj.me)"
}

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"
    try:
        requests.post(api_url, json={"chat_id": CHAT_ID, "text": msg, "parse_mode": "Markdown"}, timeout=10)
    except Exception as e:
        print(f"[!] Errore Telegram: {e}")

def scan_feed(feed_url, seen_posts):
    try:
        response = requests.get(feed_url, headers=HEADERS, timeout=15)
        if response.status_code != 200:
            print(f"[!] HTTP {response.status_code} per {feed_url}")
            return []
        
        root = ET.fromstring(response.content)
        new_posts = []
        
        # Prova formati RSS/Atom diversi
        for entry in root.findall('.//{http://www.w3.org/2005/Atom}entry') + root.findall('.//item'):
            # Estrae ID, title, link
            if entry.tag.endswith('entry'):  # Atom
                post_id = entry.find('{http://www.w3.org/2005/Atom}id')
                title_el = entry.find('{http://www.w3.org/2005/Atom}title')
                link_el = entry.find('{http://www.w3.org/2005/Atom}link')
                post_id = post_id.text if post_id is not None else ""
                title = title_el.text if title_el is not None else ""
                link = link_el.attrib.get('href', '') if link_el is not None else ""
            else:  # RSS
                post_id = entry.find('guid')
                title_el = entry.find('title')
                link_el = entry.find('link')
                post_id = post_id.text if post_id is not None else ""
                title = title_el.text if title_el is not None else ""
                link = link_el.text if link_el is not None else ""
            
            if not post_id or post_id in seen_posts:
                continue
            
            # Check keywords
            title_lower = title.lower()
            matched = None
            for kw in KEYWORDS:
                if kw in title_lower:
                    matched = kw
                    break
            
            if matched:
                send_telegram(f"*Titolo:* {title}\n*Keyword:* {matched}", link)
                new_posts.append(post_id)
            
            seen_posts.append(post_id)
        
        return new_posts
    
    except Exception as e:
        print(f"[!] Errore feed {feed_url}: {e}")
        return []

def scan_socials():
    # Carica stato
    if STATE_FILE.exists():
        with open(STATE_FILE, "r") as f:
            seen_posts = json.load(f)
    else:
        seen_posts = []
    
    print(f"[*] Post già visti: {len(seen_posts)}")
    total_new = 0
    
    for feed in RSS_FEEDS:
        print(f"[*] Scansione {feed}...")
        new = scan_feed(feed, seen_posts)
        total_new += len(new)
        print(f"    -> {len(new)} lead nuovi")
    
    # Mantieni solo ultimi 1000
    if len(seen_posts) > 1000:
        seen_posts = seen_posts[-1000:]
    
    # Salva
    with open(STATE_FILE, "w") as f:
        json.dump(seen_posts, f)
    
    print(f"[+] Fatto. {total_new} lead totali nuovi.")

if __name__ == "__main__":
    scan_socials()