"""
═══════════════════════════════════════════════════════════════════════════════
  FIXNEZA PYTHON AUTOMATION TOOLKIT — STARTER PACK (FREE)
═══════════════════════════════════════════════════════════════════════════════

  3 ready-to-use Python automation scripts to get you started.
  The full toolkit (30 scripts + video tutorials) launches soon.

  Get the full version: https://fixneza.com

  ─────────────────────────────────────────────────────────────────────────────
  WHAT'S INCLUDED IN THIS STARTER:
  1. Web Scraper — Extract product prices from any e-commerce site
  2. Email Sender — Send personalized bulk emails (with rate-limiting)
  3. CSV Cleaner — Auto-clean and deduplicate messy CSV files
  ─────────────────────────────────────────────────────────────────────────────

  REQUIREMENTS:
    Python 3.8+
    Install dependencies:
      pip install requests beautifulsoup4 pandas

  ─────────────────────────────────────────────────────────────────────────────
"""


# ═══════════════════════════════════════════════════════════════════════════════
# SCRIPT 1: WEB SCRAPER — Extract prices from any e-commerce site
# ═══════════════════════════════════════════════════════════════════════════════

def scrape_product_prices(url, css_selector):
    """
    Scrape product prices from any e-commerce page.

    Args:
        url (str): The page URL to scrape
        css_selector (str): CSS selector for the price elements
                            Example: '.price' or 'span.product-price'

    Returns:
        list: All price strings found on the page
    """
    import requests
    from bs4 import BeautifulSoup

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
                      'AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/120.0.0.0 Safari/537.36'
    }

    try:
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()

        soup = BeautifulSoup(response.text, 'html.parser')
        prices = [el.get_text(strip=True) for el in soup.select(css_selector)]

        print(f"✓ Scraped {len(prices)} prices from {url}")
        return prices

    except requests.RequestException as e:
        print(f"✗ Error scraping {url}: {e}")
        return []


# Example usage:
# prices = scrape_product_prices(
#     'https://example-shop.com/products',
#     '.product-price'
# )
# print(prices)


# ═══════════════════════════════════════════════════════════════════════════════
# SCRIPT 2: EMAIL SENDER — Send personalized bulk emails (with rate-limiting)
# ═══════════════════════════════════════════════════════════════════════════════

def send_bulk_emails(recipients, subject, body_template, smtp_config):
    """
    Send personalized bulk emails with built-in rate-limiting to avoid spam flags.

    Args:
        recipients (list): List of dicts with 'email' and 'name' keys
        subject (str): Email subject (can use {name} placeholder)
        body_template (str): Email body (can use {name} placeholder)
        smtp_config (dict): {'host', 'port', 'user', 'password'}

    Example smtp_config for Gmail:
        {
            'host': 'smtp.gmail.com',
            'port': 587,
            'user': 'you@gmail.com',
            'password': 'your-app-password'
        }
    """
    import smtplib
    import time
    from email.mime.text import MIMEText
    from email.mime.multipart import MIMEMultipart

    sent = 0
    failed = 0

    try:
        with smtplib.SMTP(smtp_config['host'], smtp_config['port']) as server:
            server.starttls()
            server.login(smtp_config['user'], smtp_config['password'])

            for recipient in recipients:
                try:
                    msg = MIMEMultipart()
                    msg['From'] = smtp_config['user']
                    msg['To'] = recipient['email']
                    msg['Subject'] = subject.format(name=recipient.get('name', ''))

                    body = body_template.format(name=recipient.get('name', ''))
                    msg.attach(MIMEText(body, 'plain'))

                    server.send_message(msg)
                    sent += 1
                    print(f"✓ Sent to {recipient['email']}")

                    # Rate-limit: 1 email per 2 seconds (avoids spam flags)
                    time.sleep(2)

                except Exception as e:
                    failed += 1
                    print(f"✗ Failed to send to {recipient['email']}: {e}")

    except Exception as e:
        print(f"✗ SMTP connection error: {e}")

    print(f"\n📊 Summary: {sent} sent, {failed} failed")
    return {'sent': sent, 'failed': failed}


# Example usage:
# recipients = [
#     {'email': 'alice@example.com', 'name': 'Alice'},
#     {'email': 'bob@example.com', 'name': 'Bob'},
# ]
#
# send_bulk_emails(
#     recipients=recipients,
#     subject="Hi {name}, quick update!",
#     body_template="Hello {name},\n\nJust wanted to share...",
#     smtp_config={
#         'host': 'smtp.gmail.com',
#         'port': 587,
#         'user': 'your@email.com',
#         'password': 'your-app-password'
#     }
# )


# ═══════════════════════════════════════════════════════════════════════════════
# SCRIPT 3: CSV CLEANER — Auto-clean and deduplicate messy CSV files
# ═══════════════════════════════════════════════════════════════════════════════

def clean_csv(input_file, output_file, dedupe_column=None):
    """
    Clean a messy CSV file:
    - Strips whitespace from all string fields
    - Removes empty rows
    - Removes duplicate rows (optionally based on a specific column)
    - Standardizes column names (lowercase, no spaces)

    Args:
        input_file (str): Path to input CSV
        output_file (str): Path to save cleaned CSV
        dedupe_column (str, optional): Column to dedupe on (e.g., 'email')
                                       If None, dedupes on all columns

    Returns:
        dict: Stats about the cleaning operation
    """
    import pandas as pd

    try:
        # Load CSV
        df = pd.read_csv(input_file)
        original_rows = len(df)

        # 1. Standardize column names
        df.columns = [col.strip().lower().replace(' ', '_') for col in df.columns]

        # 2. Strip whitespace from string fields
        for col in df.select_dtypes(include='object').columns:
            df[col] = df[col].astype(str).str.strip()

        # 3. Remove empty rows
        df = df.dropna(how='all')

        # 4. Deduplicate
        if dedupe_column and dedupe_column in df.columns:
            df = df.drop_duplicates(subset=[dedupe_column], keep='first')
        else:
            df = df.drop_duplicates(keep='first')

        # 5. Save cleaned file
        df.to_csv(output_file, index=False)

        cleaned_rows = len(df)
        removed = original_rows - cleaned_rows

        print(f"✓ Cleaned {input_file}")
        print(f"  Original rows: {original_rows}")
        print(f"  Cleaned rows: {cleaned_rows}")
        print(f"  Removed: {removed} ({(removed/original_rows*100):.1f}%)")
        print(f"  Saved to: {output_file}")

        return {
            'original': original_rows,
            'cleaned': cleaned_rows,
            'removed': removed
        }

    except Exception as e:
        print(f"✗ Error cleaning {input_file}: {e}")
        return None


# Example usage:
# clean_csv('messy_contacts.csv', 'clean_contacts.csv', dedupe_column='email')


# ═══════════════════════════════════════════════════════════════════════════════
# WANT MORE? GET THE FULL TOOLKIT
# ═══════════════════════════════════════════════════════════════════════════════
#
# This is just the starter pack. The full Python Automation Toolkit includes:
#
#   ✓ 30 production-ready scripts (PDF generation, image batch processing,
#     SEO scrapers, social media schedulers, file organizers, and more)
#   ✓ Video tutorials walking through each script
#   ✓ Lifetime updates as we add new automations
#   ✓ Discord community for help and ideas
#
# Coming soon at: https://fixneza.com
#
# Be the first to know — drop your email at fixneza.com to get early access
# and an exclusive launch discount.
#
# ═══════════════════════════════════════════════════════════════════════════════

if __name__ == '__main__':
    print("""
╔═══════════════════════════════════════════════════════════════╗
║                                                               ║
║   FIXNEZA PYTHON AUTOMATION TOOLKIT — STARTER PACK            ║
║                                                               ║
║   3 free scripts to get you started.                          ║
║   Full version (30 scripts) launches soon.                    ║
║                                                               ║
║   Get notified: https://fixneza.com                           ║
║                                                               ║
╚═══════════════════════════════════════════════════════════════╝
    """)
    print("👉 Open this file in your editor to see the 3 scripts.")
    print("👉 Read the comments at the top for setup instructions.")
    print("👉 Each script has example usage at the bottom of its section.")
