from datetime import datetime
import time
from flask import current_app, url_for
from flask_login import current_user
from flask_mail import Message
from markupsafe import escape

from . import db, mail
from .models import MailLog


def _get_current_user_id():
    try:
        if current_user and current_user.is_authenticated:
            return current_user.id
    except Exception:
        pass
    return None


def send_email(
    subject,
    recipients,
    body,
    html=None,
    module=None,
    event=None,
    related_entity_type=None,
    related_entity_id=None,
    sent_by_id=None
):
    mail_log = None

    try:
        if not recipients:
            return False, "No recipients provided.", None

        clean_recipients = [r.strip() for r in recipients if r and r.strip()]

        if not clean_recipients:
            return False, "Recipient list is empty.", None

        mail_log = MailLog(
            module=module,
            event=event,
            subject=subject,
            recipients=", ".join(clean_recipients),
            body=body,
            html=html,
            status="Pending",
            related_entity_type=related_entity_type,
            related_entity_id=related_entity_id,
            sent_by_id=sent_by_id if sent_by_id else _get_current_user_id(),
            created_at=datetime.utcnow()
        )

        db.session.add(mail_log)
        db.session.commit()

        msg = Message(
            subject=subject,
            recipients=clean_recipients,
            body=body,
            html=html
        )

        last_error = None

        # Always use a brand-new SMTP connection for this message.  Do not use
        # ``with mail.connect()`` here: Flask-Mail calls SMTP.quit() from its
        # context-manager cleanup and some Office 365 endpoints can close the
        # socket first.  When that happens, cleanup itself may raise
        # ``OSError: [Errno 5] Input/output error`` even after the message was
        # accepted.
        #
        # We also keep MAIL_MAX_EMAILS at 0.  With MAIL_MAX_EMAILS=1,
        # Flask-Mail reconnects immediately after every send, so one email can
        # consume two SMTP connections/logins.  Office 365 can throttle or
        # terminate those repeated sessions after only a handful of messages.
        for attempt in range(1, 4):
            conn = None
            try:
                conn = mail.connect()
                conn.__enter__()
                conn.send(msg)

                mail_log.status = "Sent"
                mail_log.sent_at = datetime.utcnow()
                mail_log.error_message = None
                db.session.commit()

                return True, None, mail_log.id

            except Exception as send_error:
                last_error = send_error
                current_app.logger.exception(
                    "Email send attempt %s failed for MailLog ID %s",
                    attempt,
                    mail_log.id
                )

                # A short backoff gives Office 365 time to release/throttle the
                # previous SMTP session before a completely fresh retry.
                if attempt < 3:
                    time.sleep(attempt)

            finally:
                # Best-effort SMTP cleanup.  Never allow a QUIT/close failure to
                # change a successful send into an application error.
                if conn is not None:
                    host = getattr(conn, "host", None)
                    if host is not None:
                        try:
                            host.quit()
                        except Exception:
                            try:
                                host.close()
                            except Exception:
                                pass
                        finally:
                            try:
                                conn.host = None
                            except Exception:
                                pass

        error_text = str(last_error) if last_error else "Unknown email sending error."

        mail_log.status = "Failed"
        mail_log.error_message = error_text
        db.session.commit()

        return False, error_text, mail_log.id

    except Exception as e:
        current_app.logger.exception("Email sending failed")

        error_text = str(e)

        try:
            if mail_log:
                mail_log.status = "Failed"
                mail_log.error_message = error_text
                db.session.commit()
        except Exception:
            db.session.rollback()
            current_app.logger.exception("Failed to update mail log after email failure")

        return False, error_text, mail_log.id if mail_log else None

def _safe(value, default="-"):
    return escape(value) if value not in (None, "",) else default


def send_lead_assignment_email(lead, assigned_user, assigned_by=None):
    if not assigned_user or not assigned_user.email:
        return False, "Assigned user email not found.", None

    assigned_by_name = assigned_by.name if assigned_by and assigned_by.name else "System"
    lead_url = url_for("leads.view_lead", lead_id=lead.id, _external=True)

    lead_code = lead.lead_code or "-"
    lead_name = lead.name or "-"
    company = lead.company or "-"
    email = lead.email or "-"
    phone = ((lead.phone_country or "") + " " + (lead.phone or "")).strip() or "-"
    location = lead.location or "-"
    website = lead.website or "-"
    notes = lead.notes or "-"
    status_name = getattr(lead.status, "name", "-") if getattr(lead, "status", None) else "-"
    source_name = getattr(lead.source, "name", "-") if getattr(lead, "source", None) else "-"
    service_name = getattr(lead.service, "name", "-") if getattr(lead, "service", None) else "-"
    industry_name = getattr(lead.industry, "name", "-") if getattr(lead, "industry", None) else "-"

    subject = f"New Lead Assigned | {lead_code} | {lead_name}"

    body = f"""
Hello {assigned_user.name},

A new lead has been assigned to you.

Lead Summary
------------
Lead Code: {lead_code}
Lead Name: {lead_name}
Company: {company}
Email: {email}
Phone: {phone}
Location: {location}
Website: {website}
Status: {status_name}
Source: {source_name}
Service: {service_name}
Industry: {industry_name}
Assigned By: {assigned_by_name}

Notes:
{notes if notes and notes != '-' else 'No notes added.'}

Open Lead:
{lead_url}

Regards,
Crystal Nexus
""".strip()

    html = f"""
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Lead Assignment</title>
</head>
<body style="margin:0; padding:0; background-color:#f4f6f8; font-family:Arial, Helvetica, sans-serif; color:#1f2937;">
  <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background-color:#f4f6f8; margin:0; padding:24px 0;">
    <tr>
      <td align="center">
        <table role="presentation" width="720" cellspacing="0" cellpadding="0" style="max-width:720px; width:100%; background:#ffffff; border-radius:14px; overflow:hidden; box-shadow:0 4px 18px rgba(0,0,0,0.08);">

          <tr>
            <td style="background:linear-gradient(135deg, #0d6efd 0%, #0b5ed7 55%, #084298 100%); padding:28px 32px; color:#ffffff;">
              <div style="font-size:13px; letter-spacing:0.6px; text-transform:uppercase; opacity:0.9; margin-bottom:8px;">
                Crystal Nexus Notification
              </div>
              <div style="font-size:28px; font-weight:700; line-height:1.2; margin-bottom:8px;">
                New Lead Assigned
              </div>
              <div style="font-size:15px; opacity:0.95;">
                {escape(assigned_user.name)}, a new lead has been assigned to you for follow-up.
              </div>
            </td>
          </tr>

          <tr>
            <td style="padding:28px 32px 8px 32px;">
              <table role="presentation" width="100%" cellspacing="0" cellpadding="0">
                <tr>
                  <td style="background:#f8fafc; border:1px solid #e5e7eb; border-radius:12px; padding:20px;">
                    <div style="font-size:13px; color:#6b7280; margin-bottom:6px;">Lead Code</div>
                    <div style="font-size:24px; font-weight:700; color:#111827; margin-bottom:14px;">{_safe(lead_code)}</div>

                    <div style="font-size:13px; color:#6b7280; margin-bottom:6px;">Lead Name</div>
                    <div style="font-size:18px; font-weight:600; color:#111827; margin-bottom:14px;">{_safe(lead_name)}</div>

                    <div style="font-size:13px; color:#6b7280; margin-bottom:6px;">Company</div>
                    <div style="font-size:16px; color:#111827;">{_safe(company)}</div>
                  </td>
                </tr>
              </table>
            </td>
          </tr>

          <tr>
            <td style="padding:16px 32px 8px 32px;">
              <div style="font-size:18px; font-weight:700; color:#111827; margin-bottom:14px;">
                Lead Details
              </div>

              <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="border-collapse:collapse;">
                <tr>
                  <td width="50%" valign="top" style="padding:0 8px 12px 0;">
                    <div style="background:#ffffff; border:1px solid #e5e7eb; border-radius:10px; padding:16px;">
                      <div style="font-size:12px; color:#6b7280; margin-bottom:4px;">Email</div>
                      <div style="font-size:15px; color:#111827; font-weight:600;">{_safe(email)}</div>
                    </div>
                  </td>
                  <td width="50%" valign="top" style="padding:0 0 12px 8px;">
                    <div style="background:#ffffff; border:1px solid #e5e7eb; border-radius:10px; padding:16px;">
                      <div style="font-size:12px; color:#6b7280; margin-bottom:4px;">Phone</div>
                      <div style="font-size:15px; color:#111827; font-weight:600;">{_safe(phone)}</div>
                    </div>
                  </td>
                </tr>

                <tr>
                  <td width="50%" valign="top" style="padding:0 8px 12px 0;">
                    <div style="background:#ffffff; border:1px solid #e5e7eb; border-radius:10px; padding:16px;">
                      <div style="font-size:12px; color:#6b7280; margin-bottom:4px;">Location</div>
                      <div style="font-size:15px; color:#111827; font-weight:600;">{_safe(location)}</div>
                    </div>
                  </td>
                  <td width="50%" valign="top" style="padding:0 0 12px 8px;">
                    <div style="background:#ffffff; border:1px solid #e5e7eb; border-radius:10px; padding:16px;">
                      <div style="font-size:12px; color:#6b7280; margin-bottom:4px;">Website</div>
                      <div style="font-size:15px; color:#111827; font-weight:600;">{_safe(website)}</div>
                    </div>
                  </td>
                </tr>

                <tr>
                  <td width="50%" valign="top" style="padding:0 8px 12px 0;">
                    <div style="background:#ffffff; border:1px solid #e5e7eb; border-radius:10px; padding:16px;">
                      <div style="font-size:12px; color:#6b7280; margin-bottom:4px;">Status</div>
                      <div style="font-size:15px; color:#111827; font-weight:600;">{_safe(status_name)}</div>
                    </div>
                  </td>
                  <td width="50%" valign="top" style="padding:0 0 12px 8px;">
                    <div style="background:#ffffff; border:1px solid #e5e7eb; border-radius:10px; padding:16px;">
                      <div style="font-size:12px; color:#6b7280; margin-bottom:4px;">Source</div>
                      <div style="font-size:15px; color:#111827; font-weight:600;">{_safe(source_name)}</div>
                    </div>
                  </td>
                </tr>

                <tr>
                  <td width="50%" valign="top" style="padding:0 8px 12px 0;">
                    <div style="background:#ffffff; border:1px solid #e5e7eb; border-radius:10px; padding:16px;">
                      <div style="font-size:12px; color:#6b7280; margin-bottom:4px;">Service</div>
                      <div style="font-size:15px; color:#111827; font-weight:600;">{_safe(service_name)}</div>
                    </div>
                  </td>
                  <td width="50%" valign="top" style="padding:0 0 12px 8px;">
                    <div style="background:#ffffff; border:1px solid #e5e7eb; border-radius:10px; padding:16px;">
                      <div style="font-size:12px; color:#6b7280; margin-bottom:4px;">Industry</div>
                      <div style="font-size:15px; color:#111827; font-weight:600;">{_safe(industry_name)}</div>
                    </div>
                  </td>
                </tr>
              </table>
            </td>
          </tr>

          <tr>
            <td style="padding:8px 32px 8px 32px;">
              <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background:#fff8e6; border:1px solid #f6d58a; border-radius:10px;">
                <tr>
                  <td style="padding:16px;">
                    <div style="font-size:12px; color:#8a6d1d; margin-bottom:6px; font-weight:700;">Assigned By</div>
                    <div style="font-size:15px; color:#111827; font-weight:600;">{_safe(assigned_by_name)}</div>
                  </td>
                </tr>
              </table>
            </td>
          </tr>

          <tr>
            <td style="padding:16px 32px 8px 32px;">
              <div style="font-size:18px; font-weight:700; color:#111827; margin-bottom:10px;">
                Notes
              </div>
              <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background:#f9fafb; border:1px solid #e5e7eb; border-radius:10px;">
                <tr>
                  <td style="padding:16px; font-size:14px; color:#374151; line-height:1.6;">
                    {(_safe(notes, "No notes added.")).replace(chr(10), "<br>")}
                  </td>
                </tr>
              </table>
            </td>
          </tr>

          <tr>
            <td style="padding:24px 32px 32px 32px;" align="center">
              <a href="{lead_url}"
                 style="display:inline-block; background:#0d6efd; color:#ffffff; text-decoration:none; font-size:15px; font-weight:700; padding:14px 26px; border-radius:10px;">
                 View Lead
              </a>
            </td>
          </tr>

          <tr>
            <td style="padding:18px 32px; background:#f9fafb; border-top:1px solid #e5e7eb; text-align:center; font-size:12px; color:#6b7280;">
              This is an automated CRM notification. Please log in to the system to take action.
            </td>
          </tr>

        </table>
      </td>
    </tr>
  </table>
</body>
</html>
""".strip()

    return send_email(
        subject=subject,
        recipients=[assigned_user.email],
        body=body,
        html=html,
        module="Leads",
        event="Lead Assignment",
        related_entity_type="Lead",
        related_entity_id=lead.id,
        sent_by_id=assigned_by.id if assigned_by else None
    )

# -----------------------------------------------------------------------------
# Vendor Portal emails
# -----------------------------------------------------------------------------
def send_vendor_password_reset_email(vendor, reset_url):
    if not vendor or not vendor.email:
        return False, "Vendor email not found.", None
    subject = "Reset your Crystal Nexus Vendor Portal password"
    body = f"""Hello {vendor.name},\n\nWe received a request to reset the password for your Crystal Nexus Vendor Portal account.\n\nTransId: {vendor.external_translator_id}\nReset link: {reset_url}\n\nThis link expires in 60 minutes and stops working after your password is changed.\n\nIf you did not request this, you can ignore this email.\n\nRegards,\nCrystal Nexus"""
    html = f"""<div style='font-family:Arial,sans-serif;background:#f5f7fb;padding:28px'><div style='max-width:620px;margin:auto;background:#fff;border-radius:16px;overflow:hidden'><div style='background:#103a71;color:white;padding:26px 30px'><div style='font-size:13px;opacity:.8'>CRYSTAL NEXUS</div><h2 style='margin:6px 0 0'>Vendor Portal Password Reset</h2></div><div style='padding:30px;color:#172033'><p>Hello <strong>{escape(vendor.name)}</strong>,</p><p>A password reset was requested for your Vendor Portal account.</p><p><strong>TransId:</strong> {escape(vendor.external_translator_id)}</p><p style='margin:28px 0'><a href='{escape(reset_url)}' style='background:#f58220;color:#fff;text-decoration:none;padding:13px 20px;border-radius:9px;font-weight:bold'>Reset Password</a></p><p style='color:#6d7788;font-size:13px'>This secure link expires in 60 minutes and becomes invalid after the password is changed.</p></div></div></div>"""
    return send_email(subject, [vendor.email], body, html=html, module="Vendor Portal", event="Password Reset", related_entity_type="VendorMaster", related_entity_id=vendor.id)


def send_vendor_temporary_password_email(vendor, temporary_password, login_url):
    if not vendor or not vendor.email:
        return False, "Vendor email not found.", None
    subject = "Your Crystal Nexus Vendor Portal access"
    body = f"""Hello {vendor.name},\n\nYour Crystal Nexus Vendor Portal access is ready.\n\nLogin: {login_url}\nTransId: {vendor.external_translator_id}\nTemporary Password: {temporary_password}\n\nYou will be required to create a new password after signing in.\n\nRegards,\nCrystal Nexus"""
    html = f"""<div style='font-family:Arial,sans-serif;background:#f5f7fb;padding:28px'><div style='max-width:620px;margin:auto;background:#fff;border-radius:16px;overflow:hidden'><div style='background:#103a71;color:white;padding:26px 30px'><div style='font-size:13px;opacity:.8'>CRYSTAL NEXUS</div><h2 style='margin:6px 0 0'>Vendor Portal Access</h2></div><div style='padding:30px;color:#172033'><p>Hello <strong>{escape(vendor.name)}</strong>,</p><p>Your Vendor Portal account has been activated.</p><div style='background:#f6f8fb;border-radius:12px;padding:18px;margin:20px 0'><div><strong>TransId:</strong> {escape(vendor.external_translator_id)}</div><div style='margin-top:8px'><strong>Temporary Password:</strong> {escape(temporary_password)}</div></div><p><a href='{escape(login_url)}' style='background:#f58220;color:#fff;text-decoration:none;padding:13px 20px;border-radius:9px;font-weight:bold'>Open Vendor Portal</a></p><p style='color:#6d7788;font-size:13px'>For security, you will be asked to change this temporary password immediately after signing in.</p></div></div></div>"""
    return send_email(subject, [vendor.email], body, html=html, module="Vendor Portal", event="Temporary Password", related_entity_type="VendorMaster", related_entity_id=vendor.id)
