import asyncio
from email.mime.text import MIMEText
import logging
import os
import random
import string
from dotenv import load_dotenv
from fastapi_mail import FastMail, MessageSchema
from app.config import conf
import smtplib
from email.message import EmailMessage
from app.config import settings  

load_dotenv()

# Logging setup
logging.basicConfig(level=logging.INFO)

# Mail configuration
MAIL_USERNAME = os.getenv("MAIL_USERNAME")
MAIL_PASSWORD = os.getenv("MAIL_PASSWORD")
MAIL_FROM = os.getenv("MAIL_FROM")
MAIL_PORT = int(os.getenv("MAIL_PORT", 587))
MAIL_SERVER = os.getenv("MAIL_SERVER")
MAIL_STARTTLS = os.getenv("MAIL_STARTTLS", "True").lower() == "true"
MAIL_SSL_TLS = os.getenv("MAIL_SSL_TLS", "False").lower() == "true"

RESET_OTP_EXPIRE_MINUTES = 1


def send_otp_email(to_email: str, otp: str):
    """Send OTP code to user's email using SMTP."""
    subject = "Password Reset OTP"
    body = f"Your OTP code is: {otp}\n\nThis OTP will expire in 10 minutes."

    msg = MIMEText(body)
    msg["Subject"] = subject
    msg["From"] = MAIL_FROM
    msg["To"] = to_email

    try:
        logging.info(f"Connecting to SMTP server {MAIL_SERVER}:{MAIL_PORT}...")
        with smtplib.SMTP(MAIL_SERVER, MAIL_PORT) as server:
            if MAIL_STARTTLS:
                server.starttls()
                logging.info("STARTTLS enabled")

            server.login(MAIL_USERNAME, MAIL_PASSWORD)
            server.send_message(msg)
            logging.info(f"✅ OTP email sent successfully to {to_email}")

    except Exception as e:
        logging.error(f"❌ Failed to send OTP to {to_email}: {e}")
        
def generate_random_password(length: int = 10) -> str:
    """Generate a random password with letters, digits, and punctuation."""
    chars = string.ascii_letters + string.digits + "!@#$%^&*()"
    return ''.join(random.choice(chars) for _ in range(length))


# def send_email(to_email: str, subject: str, body: str):
#     """Send an email using SMTP (example uses Gmail)."""
#     sender_email = "your_email@gmail.com"
#     sender_password = "your_app_password"  # Use App Password, not real password

#     msg = MIMEText(body)
#     msg["Subject"] = subject
#     msg["From"] = sender_email
#     msg["To"] = to_email

#     # Gmail SMTP server
#     with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
#         server.login(sender_email, sender_password)
#         server.send_message(msg)

# # RESET_OTP_EXPIRE_MINUTES = 1

# # async def send_otp_email(email: str, otp: str):
# #     """Sends OTP via email."""
# #     message = MessageSchema(
# #         subject="Password Reset OTP",
# #         recipients=[email],
# #         body=f"Your OTP for password reset is: {otp}. It is valid for {RESET_OTP_EXPIRE_MINUTES} minutes.",
# #         subtype="plain",
# #     )
# #     fm = FastMail(conf)
# #     await fm.send_message(message)

# def send_email(to: str, subject: str, body: str) -> bool:
#     try:
#         msg = EmailMessage()
#         msg["From"] = settings.MAIL_FROM
#         msg["To"] = to
#         msg["Subject"] = subject
#         msg.set_content(body)

#         with smtplib.SMTP(settings.MAIL_SERVER, settings.MAIL_PORT) as server:
#             if settings.MAIL_STARTTLS:
#                 server.starttls()

#             server.login(settings.MAIL_USERNAME, settings.MAIL_PASSWORD)
#             server.send_message(msg)

#         return True

#     except Exception as e:
#         print(f"Unexpected error sending email: {e}")
#         return False








def send_email(to: str, subject: str, body: str) -> bool:
    try:
        msg = EmailMessage()
        msg["From"] = settings.MAIL_FROM
        msg["To"] = to
        msg["Subject"] = subject
        msg.set_content(body)

        with smtplib.SMTP(settings.MAIL_SERVER, settings.MAIL_PORT) as server:
            if settings.MAIL_STARTTLS:
                server.starttls()

            server.login(settings.MAIL_USERNAME, settings.MAIL_PASSWORD)
            server.send_message(msg)

        return True

    except Exception as e:
        print(f"Unexpected error sending email: {e}")
        return False

def send_email_sync(to: str, subject: str, body: str):
        smtp_host = "smtp.stackmail.com"
        smtp_port = 587
        smtp_user = "info@compunet.solutions"
        smtp_pass = "Jn193518f"

        msg = MIMEText(body, "plain")
        msg["Subject"] = subject
        msg["From"] = smtp_user
        msg["To"] = to

        with smtplib.SMTP(smtp_host, smtp_port) as server:
            server.ehlo()
            server.starttls()
            server.ehlo()
            server.login(smtp_user, smtp_pass)
            server.sendmail(smtp_user, [to], msg.as_string())

async def send_email_async(to: str, subject: str, body: str):
        loop = asyncio.get_running_loop()
        await loop.run_in_executor(
            None,
            send_email_sync,
            to, subject, body
        )

# app/utils/email_content.py

def admin_account_created(name: str, email: str, password: str, login_url: str) -> tuple:
    subject = "Your New Account Details"
    
    body = f"""
Hello {name},

Your admin account has been created successfully.

Email: {email}
Password: {password}

Login using the link below:
{login_url}

Please log in and change your password immediately.

Thank you,
Retail Simulation Team
"""

    return subject,body