"""
Zeus-X helpers for buying Outlook/Hotmail accounts and reading verification mail.
Refresh-token flow is mandatory for mailbox access.
"""
from __future__ import annotations

import email
import imaplib
import json
import logging
import re
import threading
import time
from dataclasses import dataclass
from email.header import decode_header
from typing import Any, Dict, Iterable, List, Optional, Tuple

import requests

import config_manager

LOGGER = logging.getLogger("x_email_changer.zeus")

BASE_URL = "https://api.zeus-x.ru"
PURCHASE_ENDPOINT = f"{BASE_URL}/purchase"
DEFAULT_ACCOUNT_CODE = "HOTMAIL"
FORCED_QUANTITY = 1

MICROSOFT_TOKEN_ENDPOINTS = (
    "https://login.microsoftonline.com/common/oauth2/v2.0/token",
)
MICROSOFT_GRAPH_SCOPE = "https://graph.microsoft.com/.default"
MICROSOFT_IMAP_SCOPE = "https://outlook.office.com/IMAP.AccessAsUser.All"
GRAPH_MESSAGES_ENDPOINT = "https://graph.microsoft.com/v1.0/me/mailfolders/inbox/messages"
IMAP_HOSTS = ("outlook.office365.com", "imap-mail.outlook.com")

CODE_REGEX = re.compile(r"(?<!\d)(\d{6})(?!\d)")
TWITTER_HINT_REGEX = re.compile(r"(x\.com|twitter)", re.IGNORECASE)
VERIFY_HINT_REGEX = re.compile(r"(verification code|confirm your email|x)", re.IGNORECASE)
FOLDER_NAME_EXTRACT_REGEX = re.compile(r'"([^"]+)"\s*$')


@dataclass
class EmailOrderResult:
    ok: bool
    status_code: int
    text: str
    data: Optional[Dict[str, Any]]
    error: Optional[str] = None
    email: Optional[str] = None
    email_id: Optional[str] = None


@dataclass
class MailCheckResult:
    ok: bool
    status_code: int
    text: str
    data: Optional[Dict[str, Any]]
    attempts: int
    error: Optional[str] = None
    code: Optional[str] = None


@dataclass
class _TokenResult:
    ok: bool
    access_token: str = ""
    refresh_token: str = ""
    expires_in: int = 0
    status_code: int = 0
    error: str = ""
    text: str = ""


def _load_zeus_settings() -> Tuple[str, str]:
    cfg = config_manager.load_config()
    api_key = str(cfg.get("zeus_api_key") or "").strip()
    account_code = str(cfg.get("zeus_accountcode") or DEFAULT_ACCOUNT_CODE).strip().upper()
    if not account_code:
        account_code = DEFAULT_ACCOUNT_CODE
    return api_key, account_code


def _extract_string(value: Any) -> str:
    if value is None:
        return ""
    return str(value).strip()


def _extract_data_root(payload: Any) -> Any:
    if isinstance(payload, dict):
        return payload.get("Data")
    return payload


def _extract_account_row(payload: Any) -> Optional[Any]:
    data = _extract_data_root(payload)
    if isinstance(data, dict):
        accounts = data.get("Accounts") or data.get("accounts")
        if isinstance(accounts, list) and accounts:
            return accounts[0]
        if isinstance(accounts, dict):
            return accounts
        if any(k in data for k in ("Email", "email", "mail")):
            return data
    elif isinstance(data, list) and data:
        return data[0]
    elif isinstance(data, str) and data.strip():
        return data.strip()
    return None


def _extract_purchase_id(payload: Any) -> str:
    data = _extract_data_root(payload)
    if isinstance(data, dict):
        return _extract_string(data.get("PurchaseId") or data.get("purchase_id"))
    return ""


def _extract_mailbox_fields(payload: Any) -> Tuple[str, str, str, str, str]:
    row = _extract_account_row(payload)
    purchase_id = _extract_purchase_id(payload)
    if isinstance(row, dict):
        email_addr = _extract_string(
            row.get("Email") or row.get("email") or row.get("mail") or row.get("Address")
        )
        mailbox_password = _extract_string(
            row.get("Password")
            or row.get("password")
            or row.get("Pass")
            or row.get("pass")
            or row.get("MailPassword")
            or row.get("mail_password")
        )
        refresh_token = _extract_string(
            row.get("RefreshToken")
            or row.get("refresh_token")
            or row.get("refreshToken")
            or row.get("RToken")
        )
        client_id = _extract_string(
            row.get("ClientId")
            or row.get("client_id")
            or row.get("clientId")
            or row.get("AppId")
        )
        identifier = _extract_string(
            row.get("Id") or row.get("id") or row.get("AccountId") or row.get("account_id")
        )
        if not identifier:
            identifier = purchase_id or email_addr
        return email_addr, mailbox_password, refresh_token, client_id, identifier

    if isinstance(row, str):
        text = row.strip()
        if ":" in text:
            left, right = text.split(":", 1)
            email_addr = _extract_string(left)
            refresh_token = _extract_string(right)
            return email_addr, "", refresh_token, "", purchase_id or email_addr
        return text, "", "", "", purchase_id or text

    return "", "", "", "", purchase_id


def _extract_error(data: Any, fallback_text: str) -> str:
    if isinstance(data, dict):
        for key in ("Message", "message", "error_description", "error", "detail", "msg", "value"):
            val = data.get(key)
            if val is not None and str(val).strip():
                return str(val).strip()
    preview = " ".join((fallback_text or "").split())
    if len(preview) > 200:
        preview = preview[:197] + "..."
    return preview or "unknown_error"


def order_email_with_config() -> EmailOrderResult:
    api_key, account_code = _load_zeus_settings()
    if not api_key:
        return EmailOrderResult(False, 0, "Missing Zeus API key", None, "missing_api_key")

    params = {
        "apikey": api_key,
        "accountcode": account_code,
        # Mandatory by user request.
        "quantity": FORCED_QUANTITY,
    }
    try:
        response = requests.get(PURCHASE_ENDPOINT, params=params, timeout=40)
    except Exception as exc:
        return EmailOrderResult(False, 0, str(exc), None, str(exc))

    text = response.text
    try:
        data = response.json()
    except Exception:
        try:
            data = json.loads(text)
        except Exception:
            data = None

    ok = response.status_code == 200
    if isinstance(data, dict) and "Code" in data:
        ok = ok and int(data.get("Code") or 0) == 0
    elif isinstance(data, dict) and "status" in data:
        ok = ok and str(data.get("status") or "").lower() in {"ok", "success"}

    email_addr, mailbox_password, refresh_token, client_id, identifier = _extract_mailbox_fields(data)
    if ok and (not email_addr or not refresh_token or not client_id):
        ok = False

    error = None
    if not ok:
        error = _extract_error(data, text)
        if not error and (not refresh_token or not client_id):
            error = "missing_refresh_token_or_client_id"

    result_data: Optional[Dict[str, Any]] = None
    if isinstance(data, dict):
        result_data = {
            "mailbox": {
                "email": email_addr,
                "password": mailbox_password,
                "refresh_token": refresh_token,
                "client_id": client_id,
                "purchase_id": _extract_purchase_id(data),
                "accountcode": account_code,
            },
            "raw": data,
        }

    return EmailOrderResult(
        ok,
        response.status_code,
        text,
        result_data,
        error,
        email=email_addr or None,
        email_id=(identifier or email_addr) or None,
    )


def order_email_with_retry(max_attempts: int = 180, delay_seconds: float = 3.0) -> EmailOrderResult:
    if max_attempts <= 0:
        max_attempts = 1
    delay = delay_seconds if delay_seconds is not None else 3.0
    last_result: Optional[EmailOrderResult] = None

    for attempt in range(1, max_attempts + 1):
        result = order_email_with_config()
        last_result = result
        if result.ok:
            return result

        err_text = ((result.error or "") + " " + (result.text or "")).lower()
        if "access denied" in err_text or "invalid apikey" in err_text or "invalid api key" in err_text:
            return result

        LOGGER.warning(
            "Zeus order failed (attempt %s/%s): %s",
            attempt,
            max_attempts,
            result.error or result.text or "unknown_error",
        )
        if attempt < max_attempts:
            try:
                time.sleep(max(delay, 0))
            except Exception:
                pass

    return last_result or EmailOrderResult(False, 0, "no result", None, "no_result")


def _iter_token_payloads(
    refresh_token: str,
    client_id: str,
    client_secret: str = "",
    scope: str = MICROSOFT_GRAPH_SCOPE,
) -> Iterable[Tuple[str, Dict[str, str]]]:
    payload: Dict[str, str] = {
        "client_id": client_id,
        "grant_type": "refresh_token",
        "refresh_token": refresh_token,
        "scope": scope,
    }
    if client_secret:
        payload["client_secret"] = client_secret
    for endpoint in MICROSOFT_TOKEN_ENDPOINTS:
        yield endpoint, payload


def _request_access_token(
    refresh_token: str,
    client_id: str,
    *,
    scope: str = MICROSOFT_GRAPH_SCOPE,
) -> _TokenResult:
    cfg = config_manager.load_config()
    raw_proxy = _extract_string(cfg.get("proxy"))
    client_secret = _extract_string(cfg.get("zeus_client_secret"))
    proxy_url = ""
    if raw_proxy and raw_proxy != "YOUR_PROXY_HERE":
        if "://" in raw_proxy:
            proxy_url = raw_proxy
        else:
            parts = raw_proxy.split(":")
            if len(parts) >= 4 and parts[1].isdigit():
                host, port, user, password = parts[0], parts[1], parts[2], ":".join(parts[3:])
                proxy_url = f"http://{user}:{password}@{host}:{port}"
            else:
                proxy_url = "http://" + raw_proxy
    proxy_options: List[Optional[Dict[str, str]]] = []
    if proxy_url:
        proxy_options.append({"http": proxy_url, "https": proxy_url})
    proxy_options.append(None)

    errors: List[str] = []
    for proxies in proxy_options:
        for endpoint, payload in _iter_token_payloads(refresh_token, client_id, client_secret, scope=scope):
            try:
                headers = {
                    "Host": "login.microsoftonline.com",
                    "User-Agent": (
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                        "AppleWebKit/537.36 (KHTML, like Gecko) "
                        "Chrome/127.0.0.0 Safari/537.36"
                    ),
                    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
                }
                response = requests.post(endpoint, headers=headers, data=payload, timeout=30, proxies=proxies)
            except Exception as exc:
                errors.append(str(exc))
                continue

            text = response.text
            try:
                data = response.json()
            except Exception:
                data = None

            access_token = ""
            refresh_next = refresh_token
            expires_in = 0
            if isinstance(data, dict):
                access_token = _extract_string(data.get("access_token"))
                refresh_next = _extract_string(data.get("refresh_token")) or refresh_token
                try:
                    expires_in = int(data.get("expires_in") or 0)
                except Exception:
                    expires_in = 0

            if response.status_code == 200 and access_token:
                return _TokenResult(
                    True,
                    access_token=access_token,
                    refresh_token=refresh_next,
                    expires_in=expires_in,
                    status_code=response.status_code,
                    text=text,
                )

            err = _extract_error(data, text)
            if err:
                errors.append(err)

    dedup_errors = []
    for item in errors:
        if item and item not in dedup_errors:
            dedup_errors.append(item)
    err_msg = "; ".join(dedup_errors[-3:]) if dedup_errors else "token_refresh_failed"
    return _TokenResult(False, error=err_msg)


def _decode_mime(value: Any) -> str:
    raw = str(value or "")
    chunks = []
    for chunk, encoding in decode_header(raw):
        if isinstance(chunk, bytes):
            charset = encoding or "utf-8"
            try:
                chunks.append(chunk.decode(charset, errors="replace"))
            except Exception:
                chunks.append(chunk.decode("utf-8", errors="replace"))
        else:
            chunks.append(str(chunk))
    return "".join(chunks)


def _extract_text_from_message(message_obj: Any) -> str:
    parts = [
        _decode_mime(message_obj.get("Subject", "")),
        _decode_mime(message_obj.get("From", "")),
    ]
    if message_obj.is_multipart():
        for part in message_obj.walk():
            content_type = str(part.get_content_type() or "").lower()
            disposition = str(part.get("Content-Disposition") or "").lower()
            if "attachment" in disposition:
                continue
            if content_type not in {"text/plain", "text/html"}:
                continue
            payload = part.get_payload(decode=True)
            if payload is None:
                payload = str(part.get_payload() or "").encode("utf-8", errors="ignore")
            charset = part.get_content_charset() or "utf-8"
            try:
                parts.append(payload.decode(charset, errors="replace"))
            except Exception:
                parts.append(payload.decode("utf-8", errors="replace"))
    else:
        payload = message_obj.get_payload(decode=True)
        if payload is None:
            payload = str(message_obj.get_payload() or "").encode("utf-8", errors="ignore")
        charset = message_obj.get_content_charset() or "utf-8"
        try:
            parts.append(payload.decode(charset, errors="replace"))
        except Exception:
            parts.append(payload.decode("utf-8", errors="replace"))
    return "\n".join(parts)


def _extract_code_from_text(text: str) -> Optional[str]:
    if not text:
        return None
    match = CODE_REGEX.search(text)
    if match:
        return match.group(1)
    return None


def _short_text(value: str, limit: int = 140) -> str:
    text = " ".join((value or "").split())
    if len(text) <= limit:
        return text
    return text[: limit - 3] + "..."


def _fetch_code_via_graph(access_token: str) -> Tuple[Optional[str], str]:
    headers = {
        "Authorization": f"Bearer {access_token}",
        "Content-Type": "application/json",
    }
    params = {
        "$top": "50",
        "$orderby": "receivedDateTime desc",
        "$select": "subject,from,bodyPreview",
    }
    try:
        response = requests.get(GRAPH_MESSAGES_ENDPOINT, headers=headers, params=params, timeout=30)
    except Exception as exc:
        return None, str(exc)

    text = response.text
    if response.status_code != 200:
        return None, f"graph_status_{response.status_code}: {_short_text(text, 200)}"

    try:
        payload = response.json()
    except Exception:
        return None, "graph_json_decode_failed"

    messages = payload.get("value") if isinstance(payload, dict) else None
    if not isinstance(messages, list):
        return None, "graph_messages_missing"

    # LOGGER.info("Zeus graph inbox messages count=%s", len(messages))
    preview: List[str] = []
    parsed: List[Tuple[str, str, str]] = []
    for msg in messages:
        if not isinstance(msg, dict):
            continue
        subject = _extract_string(msg.get("subject"))
        body_preview = _extract_string(msg.get("bodyPreview"))
        sender = ""
        from_obj = msg.get("from")
        if isinstance(from_obj, dict):
            email_addr_obj = from_obj.get("emailAddress")
            if isinstance(email_addr_obj, dict):
                sender = _extract_string(email_addr_obj.get("address") or email_addr_obj.get("name"))
        parsed.append((subject, sender, body_preview))
        if len(preview) < 8:
            preview.append(f"{_short_text(sender, 60)} | {_short_text(subject, 90)}")
    # LOGGER.info("Zeus graph preview=%s", " || ".join(preview) if preview else "-")

    code = _find_code_in_messages(parsed, source_label="GRAPH")
    if code:
        return code, ""
    return None, "graph_code_not_found"


def _iter_candidate_message_ids(ids_raw: bytes, max_items: int = 120) -> Iterable[bytes]:
    ids = [item for item in (ids_raw or b"").split() if item]
    if not ids:
        return []
    return list(reversed(ids[-max_items:]))


def _find_code_in_messages(
    items: Iterable[Tuple[str, str, str]],
    *,
    source_label: str = "",
) -> Optional[str]:
    fallback_code: Optional[str] = None
    staged: List[Tuple[str, str, str]] = []
    for subject, sender, body in items:
        staged.append((subject, sender, body))
        subject_code = _extract_code_from_text(subject or "")
        sender_and_subject = f"{sender}\n{subject}"
        if subject_code and (TWITTER_HINT_REGEX.search(sender_and_subject) or VERIFY_HINT_REGEX.search(subject or "")):
            LOGGER.info(
                "Zeus code candidate matched in subject [source=%s sender=%s subject=%s].",
                source_label or "-",
                _short_text(sender or "-", 80),
                _short_text(subject or "-", 120),
            )
            return subject_code
        sender_and_subject = f"{sender}\n{subject}"
        if not (TWITTER_HINT_REGEX.search(sender_and_subject) or VERIFY_HINT_REGEX.search(subject or "")):
            continue
        merged_text = "\n".join([subject or "", sender or "", body or ""])
        code = _extract_code_from_text(merged_text)
        if code:
            LOGGER.info(
                "Zeus code candidate matched in body [source=%s sender=%s subject=%s].",
                source_label or "-",
                _short_text(sender or "-", 80),
                _short_text(subject or "-", 120),
            )
            return code

    for subject, sender, body in staged:
        merged_text = "\n".join([subject or "", sender or "", body or ""])
        code = _extract_code_from_text(merged_text)
        if not code:
            continue
        if fallback_code is None:
            fallback_code = code
            LOGGER.info(
                "Zeus fallback code candidate detected [source=%s sender=%s subject=%s].",
                source_label or "-",
                _short_text(sender or "-", 80),
                _short_text(subject or "-", 120),
            )
    return fallback_code


def _build_xoauth2_blob(email_address: str, access_token: str) -> bytes:
    blob = f"user={email_address}\x01auth=Bearer {access_token}\x01\x01"
    return blob.encode("utf-8")


def _connect_imap_oauth(email_address: str, access_token: str) -> Tuple[imaplib.IMAP4_SSL, str]:
    last_exc: Optional[Exception] = None
    for host in IMAP_HOSTS:
        client: Optional[imaplib.IMAP4_SSL] = None
        try:
            client = imaplib.IMAP4_SSL(host=host, port=993, timeout=25)
            typ, _ = client.authenticate("XOAUTH2", lambda _unused: _build_xoauth2_blob(email_address, access_token))
            if str(typ).upper() != "OK":
                raise RuntimeError(f"imap_auth_{typ}")
            LOGGER.info(
                "Zeus IMAP authenticated host=%s state=%s",
                host,
                getattr(client, "state", "-"),
            )
            try:
                client.capability()
                client.noop()
            except Exception:
                pass
            try:
                status, data = client.select("INBOX", readonly=True)
                LOGGER.info(
                    "Zeus IMAP post-auth INBOX select status=%s data=%s",
                    status,
                    _short_text(str(data), 160),
                )
            except Exception as exc:
                LOGGER.info("Zeus IMAP post-auth INBOX select exception: %s", exc)
            return client, host
        except Exception as exc:
            last_exc = exc
            try:
                if client is not None:
                    client.logout()
            except Exception:
                pass
    raise RuntimeError(str(last_exc or "imap_oauth_failed"))


def _select_mailbox(client: imaplib.IMAP4_SSL, mailbox_names: Iterable[str], *, readonly: bool = True) -> bool:
    names = list(mailbox_names)
    last_error = ""
    for mailbox in mailbox_names:
        for _ in range(3):
            try:
                status, data = client.select(mailbox, readonly=readonly)
                if status == "OK":
                    LOGGER.info(
                        "Zeus IMAP selected mailbox=%s readonly=%s",
                        mailbox,
                        readonly,
                    )
                    return True
                last_error = f"status={status} data={_short_text(str(data), 160)}"
            except Exception as exc:
                last_error = f"exception: {_short_text(str(exc), 160)}"
            try:
                client.noop()
            except Exception:
                pass
            try:
                time.sleep(0.5)
            except Exception:
                pass
    LOGGER.info(
        "Zeus IMAP select failed mailboxes=%s readonly=%s last_error=%s",
        " | ".join(names) if names else "-",
        readonly,
        _short_text(last_error or "-", 180),
    )
    return False


def _collect_message_tuples(
    client: imaplib.IMAP4_SSL,
    *,
    max_items: int = 120,
    folder_label: str = "-",
) -> List[Tuple[str, str, str]]:
    ids_raw = b""
    search_queries = [
        ("FROM", '"info@x.com"'),
        ("FROM", '"x.com"'),
        ("FROM", '"twitter.com"'),
        ("UNSEEN",),
        ("ALL",),
    ]
    selected_query = ""
    for query in search_queries:
        try:
            status, raw_ids = client.search(None, *query)
        except Exception:
            status, raw_ids = "NO", []
        candidate = raw_ids[0] if status == "OK" and raw_ids else b""
        if candidate:
            ids_raw = candidate
            selected_query = " ".join(query)
            break

    ids_total = len([item for item in ids_raw.split() if item])
    if ids_total == 0:
        LOGGER.info("Zeus IMAP folder=%s has no message ids from search.", folder_label)
        return []
    LOGGER.info(
        "Zeus IMAP folder=%s search_query=%s ids_total=%s scan_limit=%s",
        folder_label,
        selected_query or "-",
        ids_total,
        max_items,
    )

    parsed: List[Tuple[str, str, str]] = []
    preview: List[str] = []
    for msg_id in _iter_candidate_message_ids(ids_raw, max_items=max_items):
        status, payload = client.fetch(msg_id, "(BODY.PEEK[])")
        if status != "OK" or not payload:
            continue
        msg_bytes: Optional[bytes] = None
        for item in payload:
            if isinstance(item, tuple) and len(item) >= 2 and isinstance(item[1], (bytes, bytearray)):
                msg_bytes = bytes(item[1])
                break
        if not msg_bytes:
            continue
        message_obj = email.message_from_bytes(msg_bytes)
        subject = _decode_mime(message_obj.get("Subject", ""))
        sender = _decode_mime(message_obj.get("From", ""))
        body = _extract_text_from_message(message_obj)
        parsed.append((subject, sender, body))
        if len(preview) < 5:
            preview.append(f"{_short_text(sender, 60)} | {_short_text(subject, 90)}")
    LOGGER.info(
        "Zeus IMAP folder=%s fetched_messages=%s preview=%s",
        folder_label,
        len(parsed),
        " || ".join(preview) if preview else "-",
    )
    return parsed


def _list_mailboxes(client: imaplib.IMAP4_SSL) -> List[str]:
    try:
        status, items = client.list()
    except Exception:
        return []
    if status != "OK" or not items:
        return []

    result: List[str] = []
    seen = set()
    for row in items:
        text = row.decode("utf-8", errors="replace") if isinstance(row, (bytes, bytearray)) else str(row)
        mailbox = ""
        match = FOLDER_NAME_EXTRACT_REGEX.search(text)
        if match:
            mailbox = match.group(1)
        else:
            parts = text.rsplit(" ", 1)
            if parts:
                mailbox = parts[-1].strip().strip('"')
        if not mailbox:
            continue
        key = mailbox.lower()
        if key in seen:
            continue
        seen.add(key)
        result.append(mailbox)
    return result


def _search_for_code_in_imap(client: imaplib.IMAP4_SSL) -> Optional[str]:
    # First inbox, then junk/spam folders to match the manual implementation behavior.
    if _select_mailbox(client, ("INBOX", "Inbox", "inbox"), readonly=True):
        items = _collect_message_tuples(client, max_items=120, folder_label="INBOX")
        code = _find_code_in_messages(items, source_label="INBOX")
        if code:
            return code
    else:
        LOGGER.info("Zeus IMAP could not select INBOX.")

    if _select_mailbox(client, ("Junk", "Spam", "Junk Email", "Junk E-Mail", "Bulk Mail"), readonly=True):
        items = _collect_message_tuples(client, max_items=120, folder_label="JUNK/SPAM")
        code = _find_code_in_messages(items, source_label="JUNK/SPAM")
        if code:
            return code
    else:
        LOGGER.info("Zeus IMAP could not select Junk/Spam folders.")

    # Fallback: scan all mailboxes in case tenant uses localized/custom folder names.
    all_mailboxes = _list_mailboxes(client)
    LOGGER.info(
        "Zeus IMAP mailbox list count=%s preview=%s",
        len(all_mailboxes),
        " | ".join(all_mailboxes[:15]) if all_mailboxes else "-",
    )
    for mailbox in all_mailboxes:
        if mailbox.lower() in {"inbox", "junk", "spam", "junk email", "junk e-mail", "bulk mail"}:
            continue
        if not _select_mailbox(client, (mailbox,), readonly=True):
            continue
        items = _collect_message_tuples(client, max_items=120, folder_label=mailbox)
        code = _find_code_in_messages(items, source_label=mailbox)
        if code:
            return code

    return None


def wait_for_email(
    mailbox: Dict[str, Any],
    *,
    attempts: int = 180,
    interval_sec: float = 3.0,
    stop_event: Optional[threading.Event] = None,
) -> MailCheckResult:
    if attempts <= 0:
        attempts = 1
    email_address = _extract_string((mailbox or {}).get("email"))
    refresh_token = _extract_string((mailbox or {}).get("refresh_token"))
    client_id = _extract_string((mailbox or {}).get("client_id"))
    if not email_address or not refresh_token or not client_id:
        return MailCheckResult(
            False,
            0,
            "missing refresh-token mailbox credentials",
            None,
            0,
            "missing_mailbox_refresh_token",
        )

    current_refresh_token = refresh_token
    graph_access_token = ""
    graph_token_expires_at = 0.0
    last_text = ""
    last_data: Optional[Dict[str, Any]] = None

    for attempt in range(1, attempts + 1):
        if stop_event and stop_event.is_set():
            LOGGER.warning("Zeus wait cancelled after %s attempts.", attempt - 1)
            return MailCheckResult(False, 0, "cancelled", None, attempt - 1, "cancelled")

        now = time.time()
        if not graph_access_token or now >= graph_token_expires_at:
            token_result = _request_access_token(
                current_refresh_token,
                client_id,
                scope=MICROSOFT_GRAPH_SCOPE,
            )
            if not token_result.ok:
                last_text = token_result.error or "token_refresh_failed"
                last_data = {"email": email_address, "stage": "token"}
                LOGGER.warning(
                    "Zeus token refresh failed (attempt %s/%s): %s",
                    attempt,
                    attempts,
                    last_text,
                )
                try:
                    time.sleep(max(interval_sec, 0))
                except Exception:
                    pass
                continue

            graph_access_token = token_result.access_token
            current_refresh_token = token_result.refresh_token or current_refresh_token
            expires_in = token_result.expires_in if token_result.expires_in > 0 else 300
            graph_token_expires_at = time.time() + max(30, expires_in - 30)
            LOGGER.info(
                "Zeus graph token refresh ok (attempt %s/%s): expires_in=%s",
                attempt,
                attempts,
                token_result.expires_in or "-",
            )

        # token_shape = "jwt" if graph_access_token.count(".") >= 2 else "opaque"
        # LOGGER.info("Zeus graph token shape (attempt %s/%s): %s", attempt, attempts, token_shape)

        graph_code, graph_error = _fetch_code_via_graph(graph_access_token)
        if graph_code:
            return MailCheckResult(
                True,
                200,
                "ok",
                {"source": "graph", "email": email_address},
                attempt,
                None,
                graph_code,
            )

        last_text = graph_error or "graph_code_not_found"
        last_data = {"source": "graph", "email": email_address}
        # LOGGER.info("Zeus graph check attempt %s/%s: %s", attempt, attempts, last_text)
        # Force token refresh next iteration when token becomes invalid.
        lower_error = last_text.lower()
        if "invalid" in lower_error or "expired" in lower_error or "unauthorized" in lower_error:
            graph_access_token = ""
            graph_token_expires_at = 0.0

        try:
            time.sleep(max(interval_sec, 0))
        except Exception:
            pass

    return MailCheckResult(False, 0, last_text, last_data, attempts, "timeout")


__all__ = ["EmailOrderResult", "MailCheckResult", "order_email_with_config", "order_email_with_retry", "wait_for_email"]
