from __future__ import annotations

import os

try:
    from mx_otp_config import (
        OTP_SMTP_EMAIL,
        OTP_SMTP_HOST,
        OTP_SMTP_PORT,
        OTP_SMTP_USE_TLS,
        OTP_BRAND_NAME,
        OTP_CODE_TTL_SECONDS,
    )
except Exception:
    OTP_SMTP_EMAIL = "otp@moxiedigital.in"
    OTP_SMTP_HOST = "mail.moxiedigital.in"
    OTP_SMTP_PORT = 587
    OTP_SMTP_USE_TLS = True
    OTP_BRAND_NAME = "Moxie Digital"
    OTP_CODE_TTL_SECONDS = 600

from mx_security_hardening import load_secure_json, save_secure_json


def save_local_otp_smtp(password: str, *, email: str = "", host: str = "", port: int | None = None, use_tls: bool | None = None) -> None:
    """Store OTP SMTP credentials with Windows DPAPI on an admin/server PC.

    Customer builds should prefer MX_OTP_API_URL so the SMTP password never
    exists on customer machines.
    """
    payload = {
        "password": str(password or ""),
        "email": str(email or OTP_SMTP_EMAIL),
        "host": str(host or OTP_SMTP_HOST),
        "port": int(port or OTP_SMTP_PORT or 587),
        "use_tls": bool(OTP_SMTP_USE_TLS if use_tls is None else use_tls),
    }
    save_secure_json("otp_smtp.bin", payload)


def _default_otp_token() -> str:
    return ""


def load_otp_config() -> dict:
    data = {
        "email": OTP_SMTP_EMAIL,
        "host": OTP_SMTP_HOST,
        "port": int(OTP_SMTP_PORT or 587),
        "use_tls": bool(OTP_SMTP_USE_TLS),
        "brand_name": OTP_BRAND_NAME,
        "ttl_seconds": int(OTP_CODE_TTL_SECONDS or 600),
        "password": "",
    }
    local = load_secure_json("otp_smtp.bin", {}) or {}
    if isinstance(local, dict):
        data.update({k: v for k, v in local.items() if k in {"email", "host", "port", "use_tls", "password"}})

    if not str(data.get("password") or "").strip():
        data["password"] = _default_otp_token()

    # Environment variables are intended for hosted/server deployments.
    env_password = (os.environ.get("MX_OTP_SMTP_PASSWORD") or "").strip()
    if env_password:
        data["password"] = env_password
    for env_name, key in (("MX_OTP_SMTP_EMAIL", "email"), ("MX_OTP_SMTP_HOST", "host")):
        value = (os.environ.get(env_name) or "").strip()
        if value:
            data[key] = value
    try:
        if os.environ.get("MX_OTP_SMTP_PORT"):
            data["port"] = int(os.environ["MX_OTP_SMTP_PORT"])
    except Exception:
        pass

    return data
