#!/usr/bin/env python3
"""
Email Configuration Setup Script for Fire Fighting Bot
This script helps you set up email notifications.
"""

import os
import sys

def create_env_file():
    """Create .env file with user input"""
    print("🔥 Fire Fighting Bot - Email Setup")
    print("="*50)
    print()
    
    # Check if .env already exists
    env_file = '.env'
    if os.path.exists(env_file):
        overwrite = input(f"{env_file} already exists. Overwrite? (y/N): ").strip().lower()
        if overwrite != 'y':
            print("Setup cancelled.")
            return
    
    print("Please provide your email configuration:")
    print()
    
    # Get email provider choice
    print("Email Provider Options:")
    print("1. Gmail (recommended)")
    print("2. Outlook")
    print("3. Yahoo")
    print("4. Custom SMTP")
    
    choice = input("\nSelect provider (1-4): ").strip()
    
    # Set SMTP settings based on choice
    if choice == "1":
        mail_server = "smtp.gmail.com"
        mail_port = "587"
        provider_name = "Gmail"
        print(f"\n📧 Selected: {provider_name}")
        print("Note: You'll need to use an App Password, not your regular Gmail password.")
        print("Visit: https://myaccount.google.com/apppasswords")
    elif choice == "2":
        mail_server = "smtp-mail.outlook.com"
        mail_port = "587"
        provider_name = "Outlook"
        print(f"\n📧 Selected: {provider_name}")
    elif choice == "3":
        mail_server = "smtp.mail.yahoo.com"
        mail_port = "587"
        provider_name = "Yahoo"
        print(f"\n📧 Selected: {provider_name}")
    elif choice == "4":
        print(f"\n📧 Selected: Custom SMTP")
        mail_server = input("SMTP Server: ").strip()
        mail_port = input("SMTP Port (usually 587): ").strip() or "587"
        provider_name = "Custom"
    else:
        print("Invalid choice. Defaulting to Gmail.")
        mail_server = "smtp.gmail.com"
        mail_port = "587"
        provider_name = "Gmail"
    
    print()
    
    # Get email credentials
    mail_username = input("Your email address: ").strip()
    mail_password = input("Your email password (or app password): ").strip()
    
    # Get notification settings
    print()
    default_sender = input(f"Default sender email (press Enter for {mail_username}): ").strip()
    if not default_sender:
        default_sender = mail_username
    
    notification_email = input("Email to receive notifications (press Enter for same): ").strip()
    if not notification_email:
        notification_email = mail_username
    
    # Create .env content
    env_content = f"""# Fire Fighting Bot Email Configuration
# Generated by setup script

# {provider_name} SMTP Configuration
MAIL_SERVER={mail_server}
MAIL_PORT={mail_port}
MAIL_USE_TLS=true

# Email credentials
MAIL_USERNAME={mail_username}
MAIL_PASSWORD={mail_password}

# Email settings
MAIL_DEFAULT_SENDER={default_sender}
NOTIFICATION_EMAIL={notification_email}

# Database URL (optional - defaults to SQLite)
# DATABASE_URL=sqlite:///fire_log.db
"""
    
    # Write .env file
    try:
        with open(env_file, 'w') as f:
            f.write(env_content)
        
        print()
        print("✅ Configuration saved successfully!")
        print(f"Created: {env_file}")
        print()
        print("🔐 Security Note:")
        print("- The .env file contains sensitive information")
        print("- Never commit .env file to version control")
        print("- Keep your email credentials secure")
        print()
        print("🧪 Testing:")
        print("- Start your Flask application")
        print("- Trigger a fire alert to test email notifications")
        print("- Check your email inbox for notifications")
        print()
        
    except Exception as e:
        print(f"❌ Error creating .env file: {e}")
        return
    
    # Test configuration option
    test_config = input("Would you like to test the email configuration now? (y/N): ").strip().lower()
    if test_config == 'y':
        test_email_config(env_file)

def test_email_config(env_file):
    """Test email configuration"""
    try:
        print("\n🧪 Testing email configuration...")
        
        # Load environment variables from .env file
        from dotenv import load_dotenv
        load_dotenv(env_file)
        
        # Import Flask-Mail components
        from flask import Flask
        from flask_mail import Mail, Message
        
        # Create test Flask app
        test_app = Flask(__name__)
        test_app.config['MAIL_SERVER'] = os.environ.get('MAIL_SERVER')
        test_app.config['MAIL_PORT'] = int(os.environ.get('MAIL_PORT', 587))
        test_app.config['MAIL_USE_TLS'] = os.environ.get('MAIL_USE_TLS', 'true').lower() == 'true'
        test_app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME')
        test_app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD')
        test_app.config['MAIL_DEFAULT_SENDER'] = os.environ.get('MAIL_DEFAULT_SENDER')
        
        mail = Mail(test_app)
        
        with test_app.app_context():
            msg = Message(
                subject='🧪 Fire Fighting Bot - Test Email',
                recipients=[os.environ.get('NOTIFICATION_EMAIL')],
                sender=os.environ.get('MAIL_DEFAULT_SENDER')
            )
            
            msg.html = """
            <html>
            <body style="font-family: Arial, sans-serif; padding: 20px;">
                <div style="max-width: 500px; margin: 0 auto; text-align: center;">
                    <h2 style="color: #48bb78;">✅ Email Test Successful!</h2>
                    <p>Your Fire Fighting Bot email configuration is working correctly.</p>
                    <p style="color: #666;">You will now receive notifications for:</p>
                    <ul style="text-align: left; color: #666;">
                        <li>🔥 Fire Alert Events</li>
                        <li>✅ Fire Extinguished Events</li>
                    </ul>
                    <hr style="margin: 20px 0;">
                    <p style="font-size: 12px; color: #999;">
                        Fire Fighting Bot System - Automated Test Email
                    </p>
                </div>
            </body>
            </html>
            """
            
            mail.send(msg)
            print("✅ Test email sent successfully!")
            print(f"Check your inbox: {os.environ.get('NOTIFICATION_EMAIL')}")
        
    except ImportError:
        print("❌ Missing dependencies. Install with: pip install python-dotenv flask-mail")
    except Exception as e:
        print(f"❌ Email test failed: {e}")
        print("\nTroubleshooting tips:")
        print("- Verify your email credentials")
        print("- For Gmail, ensure you're using an App Password")
        print("- Check if 2-Factor Authentication is enabled")
        print("- Verify SMTP server settings")

def main():
    """Main function"""
    if len(sys.argv) > 1 and sys.argv[1] == "test":
        # Test existing configuration
        if os.path.exists('.env'):
            test_email_config('.env')
        else:
            print("❌ No .env file found. Run setup first.")
    else:
        # Run setup
        create_env_file()

if __name__ == "__main__":
    main()
