"""
SMTP login tester for HRNexus (Titan / BigRock).

Run from the folder that has manage.py:
    python test_smtp.py you@yourdomain.com

It reads the SAME settings Django uses (env vars + hrnexus/email_local.py),
then tries Titan on 465 (SSL) and 587 (STARTTLS) and tells you which works.
Nothing in your project is changed.
"""
import os
import smtplib
import sys

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hrnexus.settings")
import django
django.setup()
from django.conf import settings

host = settings.EMAIL_HOST
user = (settings.EMAIL_HOST_USER or "").strip()
pw = settings.EMAIL_HOST_PASSWORD or ""
to = sys.argv[1] if len(sys.argv) > 1 else user

print(f"Host      : {host}")
print(f"User      : {user!r}")
print(f"Password  : {len(pw)} chars, starts/ends with space? {pw != pw.strip()}")
print("-" * 50)

if not user or not pw:
    sys.exit("EMAIL_HOST_USER / EMAIL_HOST_PASSWORD empty - email_local.py load nahi ho raha.")


def attempt(port, ssl):
    label = f"{host}:{port} ({'SSL' if ssl else 'STARTTLS'})"
    try:
        s = (smtplib.SMTP_SSL(host, port, timeout=20) if ssl
             else smtplib.SMTP(host, port, timeout=20))
        if not ssl:
            s.starttls()
        s.login(user, pw.strip())
        s.sendmail(user, [to], f"Subject: HRNexus SMTP test\r\nFrom: {user}\r\nTo: {to}\r\n\r\nSMTP OK")
        s.quit()
        print(f"[OK]   {label} - login + mail sent to {to}")
        return True
    except smtplib.SMTPAuthenticationError as e:
        print(f"[FAIL] {label} - LOGIN REJECTED: {e.smtp_code} {e.smtp_error!r}")
    except Exception as e:
        print(f"[FAIL] {label} - {type(e).__name__}: {e}")
    return False


ok = attempt(465, True) | attempt(587, False)
print("-" * 50)
print("Working config mil gaya." if ok else
      "Dono fail: password/mailbox ka issue hai (code ka nahi).")