from app.v1.integrations.SMTPmailer import send_email
import os
from dotenv import load_dotenv
from typing import Optional

# Load environment variables
load_dotenv()
APP_DOMAIN = os.getenv('MY_APP_DOMAIN', 'https://www.movex.ai')

def read_template(filename):
    dir_path = os.path.dirname(os.path.realpath(__file__))  # Directory of the script
    file_path = os.path.join(dir_path, filename)
    with open(file_path, 'r', encoding='utf-8') as file:
        return file.read()

def prepare_email_content(context):
    template = read_template('email_template.htm')
    for key, value in context.items():
        template = template.replace(f'{{{key}}}', value)
    return template

# Welcome Email
def send_welcome_email(email: str, name: str):
    recipient_name = name if name else "there"
    context = {
        "recipient_name": recipient_name,
        "main_message": f"""
            <p>Welcome to MOVEX, {recipient_name}! You've successfully activated your account, and we're thrilled to have you with us.</p>
            <p>Here's what you can expect:</p>
            <ul>
                <li><strong>Comprehensive Movement Management:</strong> Our platform enables efficient handling of people, goods, and service operations.</li>
                <li><strong>AI & IoT Driven Optimization:</strong> Route planning, fleet tracking, and smart service management with cutting-edge tech.</li>
                <li><strong>Future-Ready Platform:</strong> Seamless integrations, scalability, and intelligence built-in.</li>
            </ul>
            <p>To make the most out of MOVEX, check out our <a href='{APP_DOMAIN}'>Platform</a>.</p>
            <p>If you need assistance, our support team is here to help at the <a href='{APP_DOMAIN}/support'>Support Portal</a>.</p>
            <p>Thank you for choosing MOVEX. Let’s move smarter together.</p>
        """,
        "additional_content": ""
    }
    email_body = prepare_email_content(context)
    send_email("Welcome to MOVEX!", email_body, [email])

#Send verification email
def send_verification_email(email: str, code: int):
    verification_link = f"{APP_DOMAIN}/verify?email={email}&code={code}"
    context = {
        "recipient_name": "",
        "main_message": "Thank you for signing up for MOVEX! Please verify your email address.",
        "additional_content": f"<p>Your verification code is: <strong>{code}</strong></p><p>Click <a href='{verification_link}'>here</a> to verify your email.</p>"
    }
    email_body = prepare_email_content(context)
    send_email("Verify Your MOVEX Account", email_body, [email])

# For sending invite emails
def send_invite_email(email: str, code: int, role_id: int, role_name: str, account_name: str,referral_code: Optional[str] = None):
    invitation_link = f"{APP_DOMAIN}/invite?email={email}&code={code}&referral={referral_code}"

    if role_id == 3:  # Partner or Reseller        
        main_message = f"""
            <p>You're invited to become a <strong>Partner</strong> of MOVEX!</p>
            <p>We’re excited to collaborate with you as a valued reseller or integration partner in building the future of smart mobility, logistics, and field services.</p>
            <p>As a partner, you'll gain access to:</p>
            <ul>
                <li>Partner dashboard to manage your clients</li>
                <li>Revenue-sharing programs and incentives</li>
                <li>Marketing and co-branding opportunities</li>
                <li>Priority support and training</li>
            </ul>
            <p>Your invitation code is: <strong>{code}</strong></p>
            <p>Click <a href='{invitation_link}'>here</a> to join the MOVEX Partner Network.</p>
        """

    elif role_id == 4:  # Business being invited
        main_message = f"""
            <p>Welcome to MOVEX! You’ve been invited by <strong>{account_name}</strong> to start using our intelligent mobility and service management platform.</p>
            <p>MOVEX helps businesses like yours streamline operations, manage transportation, logistics, and workforce with real-time dashboards, automation, and powerful AI & IoT integrations.</p>
            <p>Your invitation code is: <strong>{code}</strong></p>
            <p>Click <a href='{invitation_link}'>here</a> to accept the invite and activate your account.</p>
        """

    else:  # Generic User or Team Invite
        main_message = f"""
            <p>You’ve been invited to join MOVEX, the all-in-one SaaS platform for intelligent mobility and service operations.</p>
            <p>Whether you’re joining as a team member, operator, or service partner, MOVEX offers everything you need to manage fleets, jobs, and people effectively.</p>
            <p>Your invitation code is: <strong>{code}</strong></p>
            <p>Click <a href='{invitation_link}'>here</a> to join the platform.</p>
        """

    context = {
        "recipient_name": "",
        "main_message": main_message,
        "additional_content": ""
    }
    email_body = prepare_email_content(context)
    send_email("You're Invited to Join MOVEX", email_body, [email])

# For sending forgot password emails
def send_forgot_password_email(email: str, code: int):
    reset_link = f"{APP_DOMAIN}/reset-password?email={email}&code={code}"
    context = {
        "recipient_name": "",
        "main_message": "We received a request to reset your password for your MOVEX account.",
        "additional_content": f"<p>Your password reset code is: <strong>{code}</strong></p><p>Click <a href='{reset_link}'>here</a> to reset your password.</p>"
    }
    email_body = prepare_email_content(context)
    send_email("Reset Your MOVEX Password", email_body, [email])

def send_contact_email(email: str, code: int):
    reset_link = f"{APP_DOMAIN}/reset-password?email={email}&code={code}"
    context = {
        "recipient_name": "",
        "main_message": "We received a request to reset your password for your MOVEX account.",
        "additional_content": f"<p>Your password reset code is: <strong>{code}</strong></p><p>Click <a href='{reset_link}'>here</a> to reset your password.</p>"
    }
    email_body = prepare_email_content(context)
    send_email("Reset Your MOVEX Password", email_body, [email])


# Subscription Management Emails
def send_subscription_success_email(email: str, name: str, count: int, amount: float):
    recipient_name = name if name else "there"
    context = {
        "recipient_name": recipient_name,
        "main_message": f"""
            <p>We're thrilled to welcome you to the MOVEX platform! Your subscription has been activated successfully, and you're now on board to transform your operations.</p>
            <p><b>Subscription Details</b></p>
            <ul>
                <li><b>Modules Subscribed:</b> {count}</li>
                <li><b>Monthly Cost:</b> ${amount}</li>
                <li><b>Next Billing Date:</b> 30 days from now.</li>
            </ul>
            <p>Should you need any assistance, we're here for you at every step.</p>
            <p>Thank you for choosing MOVEX!</p>
        """,
        "additional_content": ""
    }
    email_body = prepare_email_content(context)
    send_email("Subscription Successful - Welcome to MOVEX!", email_body, [email])

#Payment sucess email
def send_payment_success_email(email: str, name: str, amount: float):
    context = {
        "recipient_name": name,
        "main_message": f"""
            <p>We've successfully received your payment. Thank you!</p>
            <ul>
                <li><b>Amount:</b> ${amount}</li>
            </ul>
            <p>Your MOVEX subscription remains active and fully functional.</p>
            <p>We appreciate your continued support!</p>
        """,
        "additional_content": ""
    }
    email_body = prepare_email_content(context)
    send_email("MOVEX - Payment Successful - Thank You", email_body, [email])


#Payment failure email
def send_payment_failure_email(email: str, name: str, amount: float):
    context = {
        "recipient_name": name,
        "main_message": f"""
            <p>Unfortunately, your recent payment attempt has failed.</p>
            <ul>
                <li><b>Due Amount:</b> ${amount}</li>
            </ul>
            <p>Please <a href='{APP_DOMAIN}/billing'>update your payment method</a> to continue using MOVEX without interruption.</p>
        """,
        "additional_content": ""
    }
    email_body = prepare_email_content(context)
    send_email("MOVEX Payment Failure - Action Required", email_body, [email])

#Subscription Cancellation Email
def send_subscription_cancelled_email(email: str, cancellation_details: dict):
    name = cancellation_details.get("name", "there")
    context = {
        "recipient_name": name,
        "main_message": f"""
            <p>Dear {name},</p>
            <p>We're sorry to see you go. Your MOVEX subscription has been cancelled.</p>
            <p>If this was a mistake or you need help, please <a href='{APP_DOMAIN}/support'>contact support</a>.</p>
            <p>We hope to work with you again soon.</p>
        """,
        "additional_content": ""
    }
    email_body = prepare_email_content(context)
    send_email("MOVEX Subscription Cancelled", email_body, [email])
