# ============================================================
# ADDITIVE: automatic "your login is ready" mail when an Admin / HR converts a candidate to an employee.
#
# * goes out through the COMPANY's own SMTP (People/mail_engine.send_to_person) - never the SuperAdmin mailbox
# * content is the company's own template (CompanyWelcomeMail): which details, wording, login URL
# * never breaks the conversion: every problem is returned as {sent: False, status: ...}
# * the same person is not mailed twice by the automatic trigger (a changed password or a manual resend does)
# ============================================================
import logging

from django.conf import settings
from django.utils.html import escape

from . import mail_engine as me
from .common import dept_name
from .models import CompanyEmailLog, CompanyWelcomeMail, EmployeeExtra

logger = logging.getLogger(__name__)

FIELD_LABELS = {
    "employee_code": "Employee ID", "email": "Login email", "password": "Temporary password", "role": "Role",
    "designation": "Designation", "department": "Department", "employee_type": "Employee type",
    "date_of_joining": "Date of joining", "salary": "Basic salary", "reporting_manager": "Reporting manager",
    "login_url": "Login URL",
}
DEFAULT_FIELDS = ["employee_code", "email", "password", "role", "designation", "department", "employee_type",
                  "date_of_joining", "salary", "reporting_manager", "login_url"]
PLACEHOLDERS = ["{name}", "{company}", "{email}", "{employee_code}"]
KIND = "welcome_credentials"


def get_settings(company):
    s, _ = CompanyWelcomeMail.objects.get_or_create(company=company)
    return s


def fields_of(ws):
    return [f for f in (ws.fields or DEFAULT_FIELDS) if f in FIELD_LABELS]


def _account_role(emp):
    acc = getattr(emp, "account", None)
    try:
        return acc.role if acc is not None else None
    except Exception:                                                # noqa: BLE001
        return None


def details_for(company, emp, role, ws, mask_password=False):
    """[(key, label, value)] in the company's chosen order; empty values are left out."""
    role = role or _account_role(emp)
    extra = EmployeeExtra.objects.filter(employee=emp).select_related("reporting_manager").first()
    login = (ws.login_url or getattr(settings, "SITE_BASE_URL", "") or "").strip()
    vals = {
        "employee_code": emp.employee_code, "email": emp.email,
        "password": ("********" if mask_password else emp.password) if ws.include_password and emp.password else "",
        "role": role.role_name if role else "", "designation": emp.Designation or "",
        "department": dept_name(emp) or emp.Department or "", "employee_type": emp.Employee_Type or "",
        "date_of_joining": emp.Date_of_Joining.strftime("%d %b %Y") if emp.Date_of_Joining else "",
        "salary": f"{emp.Basic_Salary:,.2f}" if ws.include_salary and emp.Basic_Salary is not None else "",
        "reporting_manager": extra.reporting_manager.name if extra and extra.reporting_manager_id else "",
        "login_url": login,
    }
    return [(k, FIELD_LABELS[k], str(vals[k])) for k in fields_of(ws) if vals.get(k)]


def _fill(text, company, emp):
    return (text.replace("{name}", emp.name or "").replace("{company}", getattr(company, "Registered_Company_Name", "") or "")
            .replace("{email}", emp.email or "").replace("{employee_code}", emp.employee_code or ""))


def build(company, emp, role=None, ws=None, mask_password=False):
    ws = ws or get_settings(company)
    rows = details_for(company, emp, role, ws, mask_password)
    subject = _fill(ws.subject, company, emp).replace("\n", " ")[:150]
    intro, footer = _fill(ws.intro, company, emp), _fill(ws.footer, company, emp)
    text = intro + "\n\n" + "\n".join(f"{label}: {value}" for _, label, value in rows) + "\n\n" + footer
    html = ("<div style=\"font-family:Arial,sans-serif;font-size:14px;color:#111\">"
            + "".join(f"<p>{escape(p)}</p>" for p in intro.split("\n\n"))
            + "<table style=\"border-collapse:collapse\">"
            + "".join(f"<tr><td style=\"padding:4px 12px 4px 0;color:#555\">{escape(label)}</td>"
                      f"<td style=\"padding:4px 0\"><b>{escape(value)}</b></td></tr>" for _, label, value in rows)
            + "</table>" + "".join(f"<p>{escape(p).replace(chr(10), '<br>')}</p>" for p in footer.split("\n\n")) + "</div>")
    return subject, text, html, rows


def send_welcome(company, emp, role=None, actor="", auto=True, force=False, password_changed=False):
    """Returns {sent, status, message, to, via, from}.  status: SENT | FAILED | NO_SMTP_CONFIG | NO_EMAIL | DISABLED | ALREADY_SENT"""
    try:
        ws = get_settings(company)
        if auto and not ws.enabled:
            return {"sent": False, "status": "DISABLED", "to": emp.email,
                    "message": "The automatic welcome email is switched off for this company."}
        if auto and not force and not password_changed and CompanyEmailLog.objects.filter(
                company=company, employee=emp, kind=KIND, status="SENT").exists():
            return {"sent": False, "status": "ALREADY_SENT", "to": emp.email,
                    "message": "The welcome email was already sent to this employee. Use the resend API to send it again."}
        subject, text, html, _ = build(company, emp, role, ws)
        return me.send_to_person(company, emp, subject, text, html, kind=KIND, actor=actor, audience="EMPLOYEE")
    except Exception as exc:                                          # noqa: BLE001 - the conversion itself must never fail
        logger.exception("welcome mail failed for employee %s", getattr(emp, "pk", None))
        return {"sent": False, "status": "FAILED", "to": getattr(emp, "email", None), "message": f"{type(exc).__name__}: {exc}"[:300]}
