import requests
import json
import os
import hashlib
from bs4 import BeautifulSoup

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

# Inserisci qui i siti delle agenzie web di Parma che vuoi spiare
COMPETITORS = [
    {"name": "Iride Digital", "url": "https://iride.digital/"},
    {"name": "Cabiria", "url": "https://www.cabiria.net/"},
    {"name": "Dexanet", "url": "https://www.dexanet.com/"},
    {"name": "Leonardo Gatti", "url": "https://www.leonardogatti.it/"},
    {"name": "The Bubble Company", "url": "https://thebubblecompany.com/"}
]

def send_telegram(text):
    url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
    requests.post(url, json={"chat_id": CHAT_ID, "text": text, "parse_mode": "Markdown"})

def get_page_hash(url):
    try:
        headers = {'User-Agent': 'Mozilla/5.0'}
        response = requests.get(url, headers=headers, timeout=10)
        # Usiamo BeautifulSoup per estrarre solo il testo (ignorando script e html)
        soup = BeautifulSoup(response.text, 'html.parser')
        text = soup.get_text(separator=' ', strip=True)
        return hashlib.md5(text.encode('utf-8')).hexdigest()
    except Exception as e:
        return None

def spy():
    # Carica lo stato precedente
    if os.path.exists(STATE_FILE):
        with open(STATE_FILE, "r") as f:
            state = json.load(f)
    else:
        state = {}

    for comp in COMPETITORS:
        name = comp["name"]
        url = comp["url"]
        
        current_hash = get_page_hash(url)
        if not current_hash:
            continue
            
        previous_hash = state.get(url)
        
        if previous_hash and current_hash != previous_hash:
            msg = f"🥷 *Allarme Spionaggio Competitor*\nL'agenzia *{name}* ha modificato il suo sito web!\nControlla subito se hanno cambiato i prezzi o aggiunto servizi: {url}"
            send_telegram(msg)
            
        state[url] = current_hash

    # Salva il nuovo stato
    with open(STATE_FILE, "w") as f:
        json.dump(state, f)

if __name__ == "__main__":
    spy()
