import requests
from bs4 import BeautifulSoup
import re
import csv
import smtplib
from email.mime.text import MIMEText
import time

# 🔍 STEP 1: SEARCH GOOGLE
def get_business_websites(query):
    headers = {"User-Agent": "Mozilla/5.0"}
    url = f"https://www.google.com/search?q={query}"

    r = requests.get(url, headers=headers)
    soup = BeautifulSoup(r.text, "html.parser")

    links = []
    for a in soup.select("a"):
        href = a.get("href")
        if href and "http" in href:
            if "google" not in href:
                links.append(href.split("&")[0].replace("/url?q=", ""))

    return list(set(links))[:20]  # limit 20

# 📧 STEP 2: EXTRACT EMAIL
def get_email(url):
    try:
        r = requests.get(url, timeout=5)
        emails = re.findall(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}", r.text)
        return emails[0] if emails else ""
    except:
        return ""

# 💾 STEP 3: SAVE CSV
def save_data(data):
    with open("leads.csv", "a", newline="") as f:
        writer = csv.writer(f)
        for row in data:
            writer.writerow(row)

# 📩 STEP 4: SEND EMAIL
def send_email(to_email, name):
    sender = "info@giftontap.com"
    password = "x+ltr2lYM~i."

    subject = f"Grow your business "

    body = f"""Hi ,

We help businesses generate more leads using Google Ads & Social Media.

Would you like to get more customers?

Regards,
Ravi
SpreadTheName.com
"""

    msg = MIMEText(body)
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = to_email

    try:
        server = smtplib.SMTP("localhost")
        server.send_message(msg)
        server.quit()
    except:
        pass

# 🚀 MAIN FLOW
def main():
    query = "restaurants in london"
    websites = get_business_websites(query)

    final_data = []

    for site in websites:
        email = get_email(site)

        if email:
            print("Found:", site, email)
            final_data.append([site, email])

            # send email
            send_email(email, site)

            time.sleep(10)  # avoid spam

    save_data(final_data)

# RUN
main()