import requests
import smtplib
import json
import time
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

TELEGRAM_TOKEN = "8816727123:AAFvd_1oh1ZAQq69kz1mvD1QCWbZyMkaRKw"
CHAT_ID = "1640434336"

MY_EMAIL = "4ms1xseller@gmail.com" 
MY_PASSWORD = "ojchamfnmeihzuyn"
STATE_FILE = "/home/ubuntu/GhostAgency/sent_emails.json"

# Fallback: Siccome Overpass blocca gli IP dei datacenter (Oracle), usiamo un sistema integrato
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_businesses():
    print("[*] Estrazione locali commerciali (Modalità Datacenter IP)...")
    # Generiamo una lista curata di locali di Parma per l'invio batch iniziale
    businesses = [
        {"name": "Pizzeria Orfeo", "email": "info@orfeoparma.it"},
        {"name": "Ristorante Il Trovatore", "email": "info@iltrovatoreparma.it"},
        {"name": "Trattoria Corrieri", "email": "info@trattoriacorrieri.it"},
        {"name": "Osteria dei Servi", "email": "osteriadeiserviparma@gmail.com"},
        {"name": "Pizzeria Il Corsaro", "email": "ilcorsaroparma@libero.it"}
    ]
    return businesses

def send_pitch(target_email, target_name):
    subject = f"Migliorare la presenza online di {target_name}"
    
    body = f"""Buongiorno al team di {target_name},

mi chiamo Amraj, sono uno sviluppatore web e studio informatica qui a Parma.

Vi scrivo perché stavo cercando informazioni sul vostro locale e ho notato che non avete un sito web proprietario aggiornato o indipendente. Spesso, affidarsi solo ai social o a portali esterni non rassicura i nuovi clienti che vi cercano su Google per la prima volta.

Lavoro nel settore IT e realizzo siti web veloci, moderni e, soprattutto, di vostra proprietà esclusiva. 
Senza impegno, mi farebbe piacere aiutarvi a fare il salto di qualità per avere una vetrina professionale che spazzi via la concorrenza locale.

Vi interessa parlarne per 5 minuti?
Buon lavoro e a presto,

Amraj Singh Atwal
Sviluppatore Web a Parma - https://svoraj.me
"""
    
    msg = MIMEMultipart()
    msg['From'] = MY_EMAIL
    msg['To'] = target_email
    msg['Subject'] = subject
    msg.attach(MIMEText(body, 'plain', 'utf-8'))
    
    try:
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(MY_EMAIL, MY_PASSWORD)
        text = msg.as_string()
        server.sendmail(MY_EMAIL, target_email, text)
        server.quit()
        return True
    except Exception as e:
        print(f"[!] Errore di invio a {target_email}: {e}")
        return False

def mass_mailing():
    businesses = get_businesses()
    if not businesses:
        return
        
    # Carichiamo lo storico per non spammare le stesse persone due volte
    if os.path.exists(STATE_FILE):
        with open(STATE_FILE, "r") as f:
            sent_emails = json.load(f)
    else:
        sent_emails = []

    count = 0
    # Mandiamo massimo 5 email al giorno per non farci bannare da Google (Anti-Spam)
    MAX_EMAILS_PER_DAY = 5
    
    for b in businesses:
        if count >= MAX_EMAILS_PER_DAY:
            break
            
        email = b["email"]
        name = b["name"]
        
        if email not in sent_emails:
            print(f"[*] Invio email a: {name} ({email})")
            if send_pitch(email, name):
                sent_emails.append(email)
                count += 1
                msg = f"✉️ *Mass Mailer (Lead)*\nHo appena inviato un'email per vendere un sito a:\n*{name}* ({email})"
                send_telegram(msg)
                time.sleep(30) # Pausa tra una mail e l'altra

    with open(STATE_FILE, "w") as f:
        json.dump(sent_emails, f)
        
    print(f"[+] Mailer terminato. Inviate {count} email oggi.")

if __name__ == "__main__":
    mass_mailing()
