"""
Email Template Preview Script
Sends all email templates in a single email for visual review
"""

import sys
import os

# Add the app directory to the path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

from app import create_app
from app.services.email_service import EmailService
from flask import current_app
import os

def generate_template_preview():
    """Generate HTML preview of all email templates"""
    
    # Sample data for templates
    sample_user_name = "John Smith"
    sample_reset_url = "https://rateright.com.au/reset-password?token=abc123xyz"
    sample_verification_url = "https://rateright.com.au/verify-email?token=def456uvw"
    
    # Get Cloudinary cloud name from config (must be called within app context)
    cloudinary_cloud_name = current_app.config.get('CLOUDINARY_CLOUD_NAME')
    if not cloudinary_cloud_name:
        cloudinary_cloud_name = 'dcys6tfcf'  # Your Cloudinary cloud name as fallback
    
    # Cloudinary logo URL - convert SVG to PNG for better email client compatibility
    # Using Cloudinary transformations: f_png converts to PNG, w_400 sets width, q_auto optimizes quality
    logo_svg = f'https://res.cloudinary.com/{cloudinary_cloud_name}/image/upload/f_png,w_400,q_auto/logo_black_i8fn48.png'
    
    # Get the actual HTML from the email service methods
    preview_html = """
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <style>
            body {
                font-family: Arial, sans-serif;
                background: #f5f5f5;
                padding: 20px;
            }
            .preview-container {
                max-width: 800px;
                margin: 0 auto;
                background: white;
                padding: 30px;
                border-radius: 10px;
            }
            .preview-header {
                background: #1e293b;
                color: white;
                padding: 20px;
                margin: -30px -30px 30px -30px;
                border-radius: 10px 10px 0 0;
            }
            .template-section {
                margin: 40px 0;
                padding: 20px;
                border: 2px solid #e5e7eb;
                border-radius: 8px;
                background: #fafafa;
            }
            .template-title {
                font-size: 24px;
                font-weight: bold;
                color: #1e293b;
                margin-bottom: 20px;
                padding-bottom: 10px;
                border-bottom: 3px solid #9acd32;
            }
            .template-content {
                background: white;
                padding: 20px;
                border-radius: 5px;
                margin-top: 15px;
            }
            .divider {
                height: 3px;
                background: linear-gradient(to right, #9acd32, #7cb342);
                margin: 50px 0;
                border-radius: 2px;
            }
        </style>
    </head>
    <body>
        <div class="preview-container">
            <div class="preview-header">
                <h1 style="margin: 0;">📧 RateRight Email Templates Preview</h1>
                <p style="margin: 10px 0 0 0; opacity: 0.9;">Visual review of all email templates</p>
            </div>
    """
    
    # Template 1: Password Reset
    preview_html += f"""
            <div class="template-section">
                <div class="template-title">1️⃣ Password Reset Email</div>
                <p><strong>Purpose:</strong> Sent when a user requests to reset their password</p>
                <p><strong>Trigger:</strong> User clicks "Forgot Password"</p>
                <div class="template-content">
    """
    
    password_reset_template = """
        <div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
            <div style="background: #ffffff; border-radius: 8px; padding: 40px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                <div style="text-align: center; margin-bottom: 30px;">
                    <img src="{logo}" alt="RateRight" style="height: 50px; width: auto;" />
                </div>
                
                <h2>Reset Your Password</h2>
                
                <p>Hi {user},</p>
                
                <p>We received a request to reset your password for your RateRight account. Click the button below to create a new password:</p>
                
                <div style="text-align: center;">
                    <a href="{reset_link}" style="display: inline-block; background: #9acd32; color: #ffffff !important; padding: 14px 28px; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 20px 0;">Reset Password</a>
                </div>
                
                <p>Or copy and paste this link into your browser:</p>
                <p style="word-break: break-all; color: #9acd32;">{reset_link}</p>
                
                <div style="background: #fef3c7; border-left: 4px solid #f59e0b; padding: 12px; margin: 20px 0; font-size: 14px;">
                    <strong>⏰ This link will expire in 1 hour</strong> for security reasons.
                </div>
                
                <p>If you didn't request a password reset, you can safely ignore this email. Your password will remain unchanged.</p>
                
                <div style="margin-top: 30px; padding: 15px 20px; background: #1e293b; color: #ffffff; border-radius: 6px; font-size: 12px; line-height: 1.6;">
                    <table style="width: 100%; border-collapse: collapse;">
                        <tr>
                            <td style="width: 50%; vertical-align: top; padding-right: 15px;">
                                <strong style="font-size: 14px;">RateRight Pty Ltd</strong><br>
                                ABN: 46 689 397 582<br>
                                <a href="https://rateright.com.au" style="color: #9acd32; text-decoration: none;">rateright.com.au</a>
                            </td>
                            <td style="width: 50%; vertical-align: top; padding-left: 15px; border-left: 1px solid #475569; font-size: 11px; color: #cbd5e1;">
                                RateRight acts as a platform facilitator only. Independent contractor relationships remain between hirers and workers.
                            </td>
                        </tr>
                    </table>
                </div>
                <p style="text-align: center; font-size: 11px; color: #64748b; margin-top: 15px;">This is an automated security message. Please do not reply.</p>
            </div>
        </div>
    """.format(logo=logo_svg, user=sample_user_name, reset_link=sample_reset_url)
    
    preview_html += password_reset_template
    preview_html += f"""
                </div>
            </div>
            <div class="divider"></div>
    """
    
    # Template 2: Email Verification
    preview_html += f"""
            <div class="template-section">
                <div class="template-title">2️⃣ Email Verification Email</div>
                <p><strong>Purpose:</strong> Sent when a new user registers to verify their email address</p>
                <p><strong>Trigger:</strong> User completes registration form</p>
                <div class="template-content">
    """
    
    verification_template = """
        <div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
            <div style="background: #ffffff; border-radius: 8px; padding: 40px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                <div style="text-align: center; margin-bottom: 30px;">
                    <img src="{logo}" alt="RateRight" style="height: 50px; width: auto;" />
                </div>
                
                <h2>Welcome to RateRight!</h2>
                
                <p>Hi {user},</p>
                
                <p>Thank you for registering with RateRight, Australia's trusted construction marketplace. To complete your registration, please verify your email address by clicking the button below:</p>
                
                <div style="text-align: center;">
                    <a href="{verify_link}" style="display: inline-block; background: #9acd32; color: #ffffff !important; padding: 14px 28px; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 20px 0;">Verify Email Address</a>
                </div>
                
                <p>Or copy and paste this link into your browser:</p>
                <p style="word-break: break-all; color: #9acd32;">{verify_link}</p>
                
                <div style="background: #f0f8e8; border-left: 4px solid #9acd32; padding: 12px; margin: 20px 0; font-size: 14px;">
                    <strong>⏰ This verification link will expire in 24 hours</strong> for security reasons.
                </div>
                
                <p>Once verified, you'll be able to log in and start using all RateRight features.</p>
                
                <p>If you didn't create an account with RateRight, you can safely ignore this email.</p>
                
                <div style="margin-top: 30px; padding: 15px 20px; background: #1e293b; color: #ffffff; border-radius: 6px; font-size: 12px; line-height: 1.6;">
                    <table style="width: 100%; border-collapse: collapse;">
                        <tr>
                            <td style="width: 50%; vertical-align: top; padding-right: 15px;">
                                <strong style="font-size: 14px;">RateRight Pty Ltd</strong><br>
                                ABN: 46 689 397 582<br>
                                <a href="https://rateright.com.au" style="color: #9acd32; text-decoration: none;">rateright.com.au</a>
                            </td>
                            <td style="width: 50%; vertical-align: top; padding-left: 15px; border-left: 1px solid #475569; font-size: 11px; color: #cbd5e1;">
                                RateRight acts as a platform facilitator only. Independent contractor relationships remain between hirers and workers.
                            </td>
                        </tr>
                    </table>
                </div>
                <p style="text-align: center; font-size: 11px; color: #64748b; margin-top: 15px;">This is an automated message. Please do not reply.</p>
            </div>
        </div>
    """.format(logo=logo_svg, user=sample_user_name, verify_link=sample_verification_url)
    
    preview_html += verification_template
    preview_html += f"""
                </div>
            </div>
            <div class="divider"></div>
    """
    
    # Template 3: Generic Notification
    preview_html += f"""
            <div class="template-section">
                <div class="template-title">3️⃣ Generic Notification Email (Fallback)</div>
                <p><strong>Purpose:</strong> Used for system notifications when no specific template exists</p>
                <p><strong>Trigger:</strong> Various notification events</p>
                <div class="template-content">
    """
    
    notification_template = """
        <html>
        <body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; line-height: 1.6; color: #333;">
            <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
                <div style="background: #ffffff; border-radius: 8px; padding: 40px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                    <div style="text-align: center; margin-bottom: 30px;">
                        <img src="{logo}" alt="RateRight" style="height: 50px; width: auto;" />
                    </div>
                    
                    <h2>Sample Notification Title</h2>
                    <p>This is a sample notification message. Notifications are used to inform users about important events such as:</p>
                    <ul>
                        <li>New job matches</li>
                        <li>Rating received</li>
                        <li>Payment updates</li>
                        <li>Security alerts</li>
                        <li>Message notifications</li>
                    </ul>
                    <div style="text-align: center;">
                        <a href="https://rateright.com.au/dashboard" style="display: inline-block; background: #9acd32; color: #ffffff !important; padding: 14px 28px; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 20px 0;">View Details</a>
                    </div>
                    
                    <div style="margin-top: 30px; padding: 15px 20px; background: #1e293b; color: #ffffff; border-radius: 6px; font-size: 12px; line-height: 1.6;">
                        <table style="width: 100%; border-collapse: collapse;">
                            <tr>
                                <td style="width: 50%; vertical-align: top; padding-right: 15px;">
                                    <strong style="font-size: 14px;">RateRight Pty Ltd</strong><br>
                                    ABN: 46 689 397 582<br>
                                    <a href="https://rateright.com.au" style="color: #9acd32; text-decoration: none;">rateright.com.au</a>
                                </td>
                                <td style="width: 50%; vertical-align: top; padding-left: 15px; border-left: 1px solid #475569; font-size: 11px; color: #cbd5e1;">
                                    RateRight acts as a platform facilitator only. Independent contractor relationships remain between hirers and workers.<br><br>
                                    <a href="https://rateright.com.au/unsubscribe" style="color: #9acd32; text-decoration: underline;">Unsubscribe</a>
                                </td>
                            </tr>
                        </table>
                    </div>
                    <p style="text-align: center; font-size: 11px; color: #64748b; margin-top: 15px;">This is an automated message. Please do not reply.</p>
                </div>
            </div>
        </body>
        </html>
    """.format(logo=logo_svg)
    
    preview_html += notification_template
    preview_html += """
                </div>
            </div>
    """
    
    # Footer
    preview_html += """
            <div style="margin-top: 50px; padding: 20px; background: #1e293b; color: white; border-radius: 8px; text-align: center;">
                <p style="margin: 0; font-size: 14px;">End of Email Templates Preview</p>
                <p style="margin: 10px 0 0 0; font-size: 12px; opacity: 0.8;">Generated on """ + str(os.popen('date').read().strip()) + """</p>
            </div>
        </div>
    </body>
    </html>
    """
    
    return preview_html


def main():
    """Main function to run the preview script"""
    print("=" * 60)
    print("📧 RateRight Email Templates Preview Tool")
    print("=" * 60)
    print()
    
    # Get email address from user
    email_address = input("Enter email address to send preview to: ").strip()
    
    if not email_address or '@' not in email_address:
        print("❌ Invalid email address. Please try again.")
        return
    
    print()
    print(f"📤 Preparing to send email template preview to: {email_address}")
    print()
    
    # Create Flask app context
    app = create_app()
    
    with app.app_context():
        # Generate preview HTML
        print("🔨 Compiling email templates...")
        preview_html = generate_template_preview()
        
        # Send email
        print("📨 Sending email...")
        success = EmailService.send_email(
            to_email=email_address,
            subject="🎨 RateRight Email Templates Preview - All Templates",
            body="Please view this email in an HTML-capable email client to see the template previews.",
            html_body=preview_html
        )
        
        print()
        if success:
            print("✅ SUCCESS! Email template preview sent successfully!")
            print(f"📬 Check your inbox at: {email_address}")
            print()
            print("📋 Templates included in preview:")
            print("   1. Password Reset Email")
            print("   2. Email Verification Email")
            print("   3. Generic Notification Email")
        else:
            print("⚠️  Email sending failed or RESEND_API_KEY not configured.")
            print()
            print("💡 If you see this message, check:")
            print("   1. RESEND_API_KEY is set in your config")
            print("   2. The API key is valid and active")
            print("   3. Check the logs for more details")
    
    print()
    print("=" * 60)


if __name__ == '__main__':
    try:
        main()
    except KeyboardInterrupt:
        print("\n\n⚠️  Script cancelled by user.")
    except Exception as e:
        print(f"\n❌ Error: {str(e)}")
        import traceback
        traceback.print_exc()
