# ============================================================
# ADDITIVE: Company welcome email
#
# Sent automatically when a SuperAdmin adds a company.
# SMTP settings live in settings.py (env vars or
# hrnexus/email_local.py) - no credentials in this file.
# ============================================================

import secrets
import string

from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.utils.html import escape


def generate_temp_password(length=10):
    """company_details.password is max_length=12, keep it <= 12."""
    alphabet = string.ascii_letters + string.digits
    return "".join(secrets.choice(alphabet) for _ in range(min(length, 12)))


def _site_url():
    return (getattr(settings, "SITE_BASE_URL", "") or "").rstrip("/")


def build_company_welcome_email(company, temp_password=None):
    """Returns (subject, text_body, html_body)."""

    name = (
        company.Registered_Company_Name
        or company.Brand_Name
        or "your company"
    )

    rows = [
        ("Company Name", company.Registered_Company_Name or "-"),
        ("Brand Name", company.Brand_Name or "-"),
        ("Company ID", company.company_id),
        ("Plan", company.get_plan_display()
            if hasattr(company, "get_plan_display") else company.plan),
        ("Status", company.get_company_status_display()
            if hasattr(company, "get_company_status_display")
            else company.company_status),
        ("Employee Limit", getattr(company, "employee_limit", "-")),
        ("Admin Limit", getattr(company, "admin_limit", "-")),
        ("HR Limit", getattr(company, "hr_limit", "-")),
        ("Device Limit", getattr(company, "device_limit", "-")),
    ]

    login_rows = [("Login Email", company.email)]

    if temp_password:
        login_rows.append(("Temporary Password", temp_password))

    site = _site_url()

    if site:
        login_rows.append(("Login URL", site))

    subject = f"Welcome to HRMS - {name} account created"

    # ---------------- plain text ----------------
    text = [f"Hello {name},", "",
            "Your company account has been created on HRMS.", "",
            "COMPANY DETAILS"]
    text += [f"  {k}: {v}" for k, v in rows]
    text += ["", "LOGIN DETAILS"]
    text += [f"  {k}: {v}" for k, v in login_rows]

    if temp_password:
        text += ["", "Please change your password after your first login."]

    text += ["", "Regards,", "HRMS Team"]

    # ---------------- html ----------------
    def table(pairs):
        return "".join(
            "<tr>"
            f"<td style='padding:6px 12px;color:#555;border-bottom:1px solid #eee'>{escape(str(k))}</td>"
            f"<td style='padding:6px 12px;border-bottom:1px solid #eee'><b>{escape(str(v))}</b></td>"
            "</tr>"
            for k, v in pairs
        )

    note = (
        "<p style='color:#b45309'>Please change your password after your first login.</p>"
        if temp_password else ""
    )

    html = (
        "<div style='font-family:Arial,sans-serif;max-width:560px;margin:auto'>"
        f"<h2 style='color:#1e40af'>Welcome, {escape(name)}!</h2>"
        "<p>Your company account has been created on HRMS.</p>"
        "<h3>Company Details</h3>"
        f"<table style='border-collapse:collapse;width:100%'>{table(rows)}</table>"
        "<h3>Login Details</h3>"
        f"<table style='border-collapse:collapse;width:100%'>{table(login_rows)}</table>"
        f"{note}"
        "<p>Regards,<br>HRMS Team</p>"
        "</div>"
    )

    return subject, "\n".join(text), html


def send_company_welcome_email(company, temp_password=None):
    """
    Sends the welcome email to the company's official email
    (falls back to the login email). Raises on SMTP failure -
    the caller decides how to surface it.
    """

    to_email = company.Company_Official_Email or company.email

    if not to_email:
        raise ValueError("Company has no email address to send to.")

    subject, text, html = build_company_welcome_email(
        company, temp_password
    )

    msg = EmailMultiAlternatives(
        subject=subject,
        body=text,
        from_email=getattr(settings, "DEFAULT_FROM_EMAIL", None),
        to=[to_email],
    )

    # Login email (if different) also gets a copy.
    if company.email and company.email.lower() != to_email.lower():
        msg.cc = [company.email]

    msg.attach_alternative(html, "text/html")
    msg.send(fail_silently=False)

    return to_email
    