import json, os, smtplib, ssl, sys


def _cfg():
    return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))


def connect(cfg):
    host = str(cfg.get("host") or "")
    port = int(cfg.get("port") or 25)
    fqdn = (str(cfg.get("fqdn") or "").strip()) or None
    tls = str(cfg.get("tls") or "None")
    ctx = None
    if cfg.get("insecure"):
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
    if tls == "SSL/TLS":
        server = smtplib.SMTP_SSL(host, port, local_hostname=fqdn, context=ctx, timeout=60)
    else:
        server = smtplib.SMTP(host, port, local_hostname=fqdn, timeout=60)
    server.ehlo()
    if tls == "STARTTLS" or str(tls).lower() == "true":
        server.starttls(context=ctx)
        server.ehlo()
    user = str(cfg.get("username") or "")
    if user:
        server.login(user, str(cfg.get("password") or ""))
    return server


def main():
    cfg = _cfg()
    if not cfg.get("host"):
        raise Exception("host is not set")
    server = connect(cfg)
    try:
        server.noop()
    finally:
        try:
            server.quit()
        except Exception:
            pass
    print(json.dumps({"ok": True, "host": cfg.get("host"), "tls": cfg.get("tls") or "None"}))


try:
    main()
except smtplib.SMTPException as e:
    print(json.dumps({"error": "SMTP error: " + str(e)}))
    sys.exit(1)
except Exception as e:
    print(json.dumps({"error": str(e)}))
    sys.exit(1)
