from __future__ import annotations

import asyncio
import inspect
import json
import logging
import random
import re
import threading
import time
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple

import config_manager
from tid_provider import TransactionIdError, TransactionIdProvider
from tls_client_manager import TLSClient, TLSClientConfigError
from xpff_header import xpff_header_generator
import anymessage_service
import mailtm_service
import zeus_service
try:
    from colorama import Fore, Style, init as colorama_init
    colorama_init(autoreset=True)
except Exception:
    class _Color:
        RED = ""
        GREEN = ""
        YELLOW = ""
        CYAN = ""
        RESET_ALL = ""
    Fore = _Color()
    Style = _Color()

LOGGER = logging.getLogger("x_email_changer.email_changer")

_CT0_REGEX = re.compile(r"ct0=([^;]+)", re.IGNORECASE)
_TXID_PROVIDER: Optional[TransactionIdProvider] = None
_TXID_PROVIDER_TIMEOUT: Optional[float] = None
_TXID_PROVIDER_LOCK = threading.Lock()


@dataclass
class _RequestContext:
    session: Any


@dataclass
class EmailChangeResult:
    ok: bool
    email: str = ""
    email_id: str = ""
    mail_password: str = ""
    ct0: str = ""
    error: str = ""
    locked: bool = False


def _resolve_user_agent(user_agent: Optional[str]) -> str:
    cfg = config_manager.load_config()
    ua = user_agent or cfg.get("user_agent") or ""
    ua = ua.strip()
    if not ua:
        raise ValueError("user_agent config is missing or empty.")
    return ua


def _resolve_mail_service(cfg: Dict[str, Any]) -> str:
    anymessage_enabled = bool(cfg.get("mail_service_anymessage"))
    mailtm_enabled = bool(cfg.get("mail_service_mailtm"))
    zeus_enabled = bool(cfg.get("mail_service_zeus"))
    if sum(int(v) for v in (anymessage_enabled, mailtm_enabled, zeus_enabled)) > 1:
        raise ValueError("Multiple mail services are enabled.")
    if mailtm_enabled:
        return "mailtm"
    if anymessage_enabled:
        return "anymessage"
    if zeus_enabled:
        return "zeus"

    legacy = str(cfg.get("mail_service") or "").strip().lower()
    if legacy in {"mailtm", "mail_tm", "mail-tm"}:
        return "mailtm"
    if legacy in {"anymessage", "any_message", "any-message"}:
        return "anymessage"
    if legacy in {"zeus", "zeus-x", "zeus_x"}:
        return "zeus"
    raise ValueError("No mail service is enabled.")


def _resolve_mail_wait_settings(cfg: Dict[str, Any]) -> Tuple[int, float]:
    attempts = int(cfg.get("mail_wait_attempts", 180) or 180)
    if attempts <= 0:
        attempts = 180
    interval = float(cfg.get("mail_wait_interval_sec", 3.0) or 3.0)
    if interval <= 0:
        interval = 3.0
    return attempts, interval


def _get_txid_provider(timeout: Optional[float]) -> TransactionIdProvider:
    global _TXID_PROVIDER, _TXID_PROVIDER_TIMEOUT
    with _TXID_PROVIDER_LOCK:
        if _TXID_PROVIDER is None or _TXID_PROVIDER_TIMEOUT != timeout:
            _TXID_PROVIDER = TransactionIdProvider(_RequestContext(session=None), timeout=timeout)
            _TXID_PROVIDER_TIMEOUT = timeout
    return _TXID_PROVIDER


def _log_body(label: str, body: str, limit: int = 800) -> None:
    snippet = body if len(body) <= limit else body[:limit] + "...[truncated]"
    LOGGER.info("%s: %s", label, snippet)


def _log_response(label: str, status_code: Optional[int], body: str, limit: int = 800) -> None:
    LOGGER.info("%s status: %s", label, status_code)
    _log_body(f"{label} body", body, limit=limit)


def _resolve_response_text(response: Any) -> str:
    text_attr = getattr(response, "text", "")
    text_value: Any = text_attr
    if callable(text_attr) and not isinstance(text_attr, (str, bytes, bytearray)):
        text_value = text_attr()
    if inspect.isawaitable(text_value):
        try:
            asyncio.get_running_loop()
        except RuntimeError:
            async def _await_any(value: Any) -> Any:
                return await value
            text_value = asyncio.run(_await_any(text_value))
        else:
            LOGGER.error("Async response coroutine cannot be awaited inside the active event loop.")
            raise Exception("Cannot await async response in a running event loop.")
    if text_value is None:
        return ""
    if isinstance(text_value, str):
        return text_value
    try:
        return text_value.decode("utf-8")
    except Exception:
        return str(text_value)


def _shuffle_headers(headers: Dict[str, str]) -> Dict[str, str]:
    items = list(headers.items())
    random.shuffle(items)
    return dict(items)

def _color_text(text: str, color: str) -> str:
    if not color:
        return text
    return f"{color}{text}{Style.RESET_ALL}"


def _log_step(user_id: int, step: str, message: str, level: str = "info", color: str = "") -> None:
    thread_name = threading.current_thread().name
    prefix = f"[email][{thread_name}][user_id={user_id}][{step}] "
    msg = _color_text(prefix + message, color)
    if level == "error":
        LOGGER.error("%s", msg)
    elif level == "warning":
        LOGGER.warning("%s", msg)
    else:
        LOGGER.info("%s", msg)


def _is_cancelled(stop_event: Optional[threading.Event]) -> bool:
    return bool(stop_event and stop_event.is_set())


def _should_retry_exception(exc: Exception) -> bool:
    msg = str(exc).lower()
    retry_hints = (
        "is_connect error",
        "is_timeout error",
        "timedout",
        "timeout",
        "ssl",
        "certificate",
        "connect",
        "handshake",
    )
    return any(hint in msg for hint in retry_hints)


def _post_with_retry(
    session: Any,
    url: str,
    *,
    headers: Dict[str, str],
    json_payload: Dict[str, Any],
    timeout: Optional[float],
    label: str,
    attempts: int = 3,
    base_delay: float = 1.0,
) -> Optional[Any]:
    last_exc: Optional[Exception] = None
    for attempt in range(1, attempts + 1):
        try:
            return session.post(url, headers=headers, json=json_payload, timeout=timeout)
        except Exception as exc:
            last_exc = exc
            if not _should_retry_exception(exc) or attempt >= attempts:
                LOGGER.error("%s request failed: %s", label, exc)
                return None
            LOGGER.warning("%s error (retry %s/%s): %s", label, attempt, attempts - 1, exc)
            time.sleep(base_delay * (2 ** (attempt - 1)))
    if last_exc:
        LOGGER.error("%s request failed: %s", label, last_exc)
    return None


def _parse_error_from_body(body: str) -> Tuple[Optional[str], Optional[str]]:
    if not body:
        return None, None
    try:
        data = json.loads(body)
    except Exception:
        return None, None
    if isinstance(data, dict):
        errors = data.get("errors")
        if isinstance(errors, list) and errors:
            err = errors[0] if isinstance(errors[0], dict) else {}
            code = err.get("code") or err.get("name")
            msg = err.get("message") or err.get("description")
            return str(code) if code is not None else None, str(msg) if msg else None
        err = data.get("error")
        if isinstance(err, str):
            code = data.get("code")
            return str(code) if code is not None else None, err
        if isinstance(err, dict):
            code = err.get("code") or err.get("name")
            msg = err.get("message") or err.get("description")
            return str(code) if code is not None else None, str(msg) if msg else None
    return None, None


def _extract_subtask_ids(body: str) -> List[str]:
    if not body:
        return []
    try:
        data = json.loads(body)
    except Exception:
        return []
    if not isinstance(data, dict):
        return []
    subtasks = data.get("subtasks")
    if not isinstance(subtasks, list):
        return []
    ids: List[str] = []
    for item in subtasks:
        if isinstance(item, dict):
            subtask_id = item.get("subtask_id")
            if isinstance(subtask_id, str) and subtask_id:
                ids.append(subtask_id)
    return ids


def _log_error_if_any(label: str, body: str, status_code: Optional[int]) -> bool:
    code, msg = _parse_error_from_body(body)
    if not code and not msg:
        return False
    msg_norm = (msg or "").lower()
    category = None
    if "rate limit" in msg_norm or (status_code == 429) or code in {"88", "429"}:
        category = "rate_limit"
    elif "challenge" in msg_norm or "captcha" in msg_norm or "verify" in msg_norm:
        category = "challenge"
    detail = f"{code or '-'} | {msg or '-'}"
    colored = _color_text(detail, Fore.YELLOW)
    if category:
        LOGGER.warning("%s error (%s): %s", label, category, colored)
    else:
        LOGGER.warning("%s error: %s", label, colored)
    return True


def _requires_email_verify_input(error_code: Optional[str], error_message: Optional[str]) -> bool:
    if str(error_code or "").strip() != "366":
        return False
    message_norm = str(error_message or "").lower()
    return "emailassocverifyemail" in message_norm and "not provided" in message_norm


def _normalize_proxy(raw: str) -> str:
    s = (raw or "").strip()
    if not s or s == "YOUR_PROXY_HERE":
        raise ValueError("Proxy is empty or not configured.")
    if "random" in s:
        import random as _rnd
        import string as _str
        token = "".join(_rnd.choice(_str.ascii_letters + _str.digits) for _ in range(14))
        s = s.replace("random", token, 1)
    if "://" not in s:
        parts = s.split(":")
        if len(parts) >= 4 and parts[1].isdigit():
            host, port, user, password = parts[0], parts[1], parts[2], ":".join(parts[3:])
            return f"http://{user}:{password}@{host}:{port}"
    if s.startswith(("http://", "https://")):
        return s
    return "http://" + s


def _apply_proxy_to_session(session: Any, proxy_url: str) -> None:
    applied = False
    proxies_mapping = {"http": proxy_url, "https": proxy_url}
    try:
        if hasattr(session, "proxies") and isinstance(getattr(session, "proxies"), dict):
            session.proxies.update(proxies_mapping)
            applied = True
            LOGGER.info("Proxy applied via session.proxies: %s", proxy_url)
    except Exception as e:
        LOGGER.debug("session.proxies.update error: %s", e)

    if not applied and hasattr(session, "set_proxy"):
        try:
            try:
                session.set_proxy(proxy_url)
            except TypeError:
                session.set_proxy(proxy_url, "http")
                session.set_proxy(proxy_url, "https")
            applied = True
            LOGGER.info("Proxy applied via session.set_proxy: %s", proxy_url)
        except Exception as e:
            LOGGER.debug("session.set_proxy error: %s", e)

    if not applied:
        try:
            import os
            os.environ["HTTP_PROXY"] = proxy_url
            os.environ["HTTPS_PROXY"] = proxy_url
            applied = True
            LOGGER.info("Proxy applied via environment variables: %s", proxy_url)
        except Exception as e:
            LOGGER.debug("Error setting environment variable: %s", e)

    if not applied:
        LOGGER.error("Proxy could not be applied to session; session type not supported.")
        raise Exception("Proxy could not be applied to the session.")


def _create_tls_session(user_agent: str) -> Any:
    try:
        client = TLSClient()
    except TLSClientConfigError as exc:
        LOGGER.error("TLS client could not be started: %s", exc)
        raise
    except Exception as exc:
        LOGGER.error("TLS client creation failed: %s", exc)
        raise
    if client.session is None:
        LOGGER.error("TLS client did not return a session.")
        raise Exception("TLSClient did not return a session.")
    try:
        if hasattr(client.session, "headers"):
            client.session.headers.update({"user-agent": user_agent})
    except Exception:
        pass
    return client.session


def _extract_ct0_from_response(session: Any, response: Any) -> Optional[str]:
    try:
        resp_cookie = getattr(response, "cookies", None)
        if resp_cookie and hasattr(resp_cookie, "get"):
            found = resp_cookie.get("ct0")
            if found:
                return str(found)
    except Exception:
        pass

    try:
        sess_cookie = getattr(session, "cookies", None)
        if sess_cookie and hasattr(sess_cookie, "get"):
            found = sess_cookie.get("ct0")
            if found:
                return str(found)
    except Exception:
        pass

    try:
        headers = getattr(response, "headers", None) or {}
        set_cookie = headers.get("set-cookie") if isinstance(headers, dict) else None
        if set_cookie:
            match = _CT0_REGEX.search(str(set_cookie))
            if match:
                return match.group(1)
    except Exception:
        pass
    return None


def _extract_guest_id(session: Any) -> Optional[str]:
    try:
        return session.cookies.get("guest_id") or session.cookies.get("gt")
    except Exception:
        return None


def _is_account_locked_error(body: str) -> bool:
    code, msg = _parse_error_from_body(body)
    msg_norm = (msg or "").lower()
    if "temporarily locked" in msg_norm:
        return True
    if code in {"326"}:
        return True
    if "account is temporarily locked" in (body or "").lower():
        return True
    return False


def _start_add_email_flow(session: Any, *, ct0: str, user_agent: str,
                          transaction_id: Optional[str], timeout: Optional[float]) -> Tuple[Optional[str], Optional[str], Optional[int], bool, List[str]]:
    url = "https://api.x.com/1.1/onboarding/task.json?flow_name=add_email"
    headers = _shuffle_headers({
        "authorization": (
            "Bearer "
            "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs=1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
        ),
        "x-csrf-token": ct0,
        "accept-language": "en-US",
        "sec-ch-ua": '"Google Chrome";v="142", "Chromium";v="142", "Not A(Brand";v="24"',
        "x-twitter-client-language": "en",
        "sec-ch-ua-mobile": "?0",
        "x-twitter-active-user": "yes",
        "x-twitter-auth-type": "OAuth2Session",
        "user-agent": user_agent,
        "accept": "*/*",
        "origin": "https://x.com",
        "sec-fetch-site": "same-site",
        "sec-fetch-mode": "cors",
        "sec-fetch-dest": "empty",
        "referer": "https://x.com/",
        "accept-encoding": "gzip, deflate, br",
        "priority": "u=1, i",
        "content-type": "application/json",
    })
    if transaction_id:
        headers["x-client-transaction-id"] = transaction_id

    payload = {
        "input_flow_data": {
            "flow_context": {
                "debug_overrides": {},
                "start_location": {
                    "location": "settings"
                }
            }
        },
        "subtask_versions": {
            "action_list": 2,
            "alert_dialog": 1,
            "app_download_cta": 1,
            "check_logged_in_account": 1,
            "choice_selection": 3,
            "contacts_live_sync_permission_prompt": 0,
            "cta": 7,
            "email_verification": 2,
            "end_flow": 1,
            "enter_date": 1,
            "enter_email": 2,
            "enter_password": 5,
            "enter_phone": 2,
            "enter_recaptcha": 1,
            "enter_text": 5,
            "enter_username": 2,
            "generic_urt": 3,
            "in_app_notification": 1,
            "interest_picker": 3,
            "js_instrumentation": 1,
            "menu_dialog": 1,
            "notifications_permission_prompt": 2,
            "open_account": 2,
            "open_home_timeline": 1,
            "open_link": 1,
            "phone_verification": 4,
            "privacy_options": 1,
            "security_key": 3,
            "select_avatar": 4,
            "select_banner": 2,
            "settings_list": 7,
            "show_code": 1,
            "sign_up": 2,
            "sign_up_review": 4,
            "tweet_selection_urt": 1,
            "update_users": 1,
            "upload_media": 1,
            "user_recommendations_list": 4,
            "user_recommendations_urt": 1,
            "wait_spinner": 3,
            "web_modal": 1
        }
    }
    resp = _post_with_retry(
        session,
        url,
        headers=headers,
        json_payload=payload,
        timeout=timeout,
        label="add_email start",
    )
    if resp is None:
        return None, None, None, False, []
    status_code = getattr(resp, "status_code", None)
    body_txt = _resolve_response_text(resp)
    _log_response("add_email_start", status_code, body_txt)
    is_locked = _is_account_locked_error(body_txt)
    if _log_error_if_any("add_email_start", body_txt, status_code):
        return None, _extract_ct0_from_response(session, resp), status_code, is_locked, _extract_subtask_ids(body_txt)
    new_ct0 = _extract_ct0_from_response(session, resp)
    flow_token: Optional[str] = None
    try:
        data = json.loads(body_txt) if body_txt else {}
        flow_token = data.get("flow_token")
    except Exception:
        flow_token = None
    return flow_token, new_ct0, status_code, is_locked, _extract_subtask_ids(body_txt)


def _submit_add_email_password(session: Any, *, ct0: str, user_agent: str,
                               transaction_id: Optional[str], flow_token: str,
                               password: str, xpff_token: Optional[str],
                               timeout: Optional[float]) -> Tuple[bool, Optional[str], Optional[int], Optional[str]]:
    url = "https://api.x.com/1.1/onboarding/task.json"
    headers = _shuffle_headers({
        "authorization": (
            "Bearer "
            "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs=1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
        ),
        "x-csrf-token": ct0,
        "accept-language": "en-US",
        "sec-ch-ua": '"Google Chrome";v="142", "Chromium";v="142", "Not A(Brand";v="24"',
        "x-twitter-client-language": "en",
        "sec-ch-ua-mobile": "?0",
        "x-twitter-active-user": "yes",
        "x-twitter-auth-type": "OAuth2Session",
        "user-agent": user_agent,
        "accept": "*/*",
        "origin": "https://x.com",
        "sec-fetch-site": "same-site",
        "sec-fetch-mode": "cors",
        "sec-fetch-dest": "empty",
        "referer": "https://x.com/",
        "accept-encoding": "gzip, deflate, br",
        "priority": "u=1, i",
        "content-type": "application/json",
    })
    if transaction_id:
        headers["x-client-transaction-id"] = transaction_id
    if xpff_token:
        headers["x-xp-forwarded-for"] = xpff_token

    payload = {
        "flow_token": flow_token,
        "subtask_inputs": [
            {
                "subtask_id": "DeviceAssocEnterPassword",
                "enter_password": {
                    "password": password,
                    "link": "next_link",
                },
            }
        ],
    }
    resp = _post_with_retry(
        session,
        url,
        headers=headers,
        json_payload=payload,
        timeout=timeout,
        label="add_email password",
    )
    if resp is None:
        return False, None, None, None
    status_code = getattr(resp, "status_code", None)
    body_txt = _resolve_response_text(resp)
    _log_response("add_email_password", status_code, body_txt)
    error_found = _log_error_if_any("add_email_password", body_txt, status_code)
    new_ct0 = _extract_ct0_from_response(session, resp)
    flow_token_next: Optional[str] = None
    try:
        data = json.loads(body_txt) if body_txt else {}
        flow_token_next = data.get("flow_token")
    except Exception:
        flow_token_next = None
    success = status_code is not None and 200 <= status_code < 300 and not error_found
    return success, new_ct0, status_code, flow_token_next


def _submit_email_enter(session: Any, *, email: str, flow_token: str,
                        ct0: str, user_agent: str, transaction_id: Optional[str],
                        xpff_token: Optional[str], timeout: Optional[float]) -> Tuple[bool, Optional[str], Optional[int], Optional[str], Optional[str], Optional[str]]:
    url = "https://api.x.com/1.1/onboarding/task.json"
    headers = _shuffle_headers({
        "authorization": (
            "Bearer "
            "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs=1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
        ),
        "x-csrf-token": ct0,
        "accept-language": "en-US",
        "sec-ch-ua": '"Google Chrome";v="142", "Chromium";v="142", "Not A(Brand";v="24"',
        "sec-ch-ua-platform": '"Windows"',
        "sec-ch-ua-mobile": "?0",
        "x-twitter-client-language": "en",
        "x-twitter-active-user": "yes",
        "x-twitter-auth-type": "OAuth2Session",
        "user-agent": user_agent,
        "accept": "*/*",
        "origin": "https://x.com",
        "sec-fetch-site": "same-site",
        "sec-fetch-mode": "cors",
        "sec-fetch-dest": "empty",
        "referer": "https://x.com/",
        "accept-encoding": "gzip, deflate, br",
        "priority": "u=1, i",
        "content-type": "application/json",
    })
    if transaction_id:
        headers["x-client-transaction-id"] = transaction_id
    if xpff_token:
        headers["x-xp-forwarded-for"] = xpff_token

    payload = {
        "flow_token": flow_token,
        "subtask_inputs": [
            {
                "subtask_id": "EmailAssocEnterEmail",
                "enter_email": {
                    "setting_responses": [
                        {
                            "key": "email_discoverability_setting",
                            "response_data": {
                                "boolean_data": {"result": False}
                            }
                        }
                    ],
                    "email": email,
                    "link": "next_link",
                },
            }
        ],
    }
    resp = _post_with_retry(
        session,
        url,
        headers=headers,
        json_payload=payload,
        timeout=timeout,
        label="EmailAssocEnterEmail",
    )
    if resp is None:
        return False, None, None, None, None, None
    status_code = getattr(resp, "status_code", None)
    body_txt = _resolve_response_text(resp)
    _log_response("email_enter", status_code, body_txt)
    error_code, error_message = _parse_error_from_body(body_txt)
    error_found = _log_error_if_any("email_enter", body_txt, status_code)
    new_ct0 = _extract_ct0_from_response(session, resp)
    flow_token_next: Optional[str] = None
    try:
        data = json.loads(body_txt) if body_txt else {}
        flow_token_next = data.get("flow_token")
    except Exception:
        flow_token_next = None
    success = status_code is not None and 200 <= status_code < 300 and not error_found
    return success, new_ct0, status_code, flow_token_next, error_code, error_message


def _submit_email_verify(session: Any, *, email: str, code: str, flow_token: str,
                         ct0: str, user_agent: str, transaction_id: Optional[str],
                         xpff_token: Optional[str], timeout: Optional[float]) -> Tuple[bool, Optional[str], Optional[int], Optional[str]]:
    url = "https://api.x.com/1.1/onboarding/task.json"
    headers = _shuffle_headers({
        "authorization": (
            "Bearer "
            "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs=1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
        ),
        "x-csrf-token": ct0,
        "accept-language": "en-US",
        "sec-ch-ua": '"Google Chrome";v="142", "Chromium";v="142", "Not A(Brand";v="24"',
        "sec-ch-ua-platform": '"Windows"',
        "sec-ch-ua-mobile": "?0",
        "x-twitter-client-language": "en",
        "x-twitter-active-user": "yes",
        "x-twitter-auth-type": "OAuth2Session",
        "user-agent": user_agent,
        "accept": "*/*",
        "origin": "https://x.com",
        "sec-fetch-site": "same-site",
        "sec-fetch-mode": "cors",
        "sec-fetch-dest": "empty",
        "referer": "https://x.com/",
        "accept-encoding": "gzip, deflate, br",
        "priority": "u=1, i",
        "content-type": "application/json",
    })
    if transaction_id:
        headers["x-client-transaction-id"] = transaction_id
    if xpff_token:
        headers["x-xp-forwarded-for"] = xpff_token

    payload = {
        "flow_token": flow_token,
        "subtask_inputs": [
            {
                "subtask_id": "EmailAssocVerifyEmail",
                "email_verification": {
                    "code": code,
                    "email": email,
                    "link": "next_link",
                },
            }
        ],
    }
    resp = _post_with_retry(
        session,
        url,
        headers=headers,
        json_payload=payload,
        timeout=timeout,
        label="EmailAssocVerifyEmail",
    )
    if resp is None:
        return False, None, None, None
    status_code = getattr(resp, "status_code", None)
    body_txt = _resolve_response_text(resp)
    _log_response("email_verify", status_code, body_txt)
    error_found = _log_error_if_any("email_verify", body_txt, status_code)
    new_ct0 = _extract_ct0_from_response(session, resp)
    flow_token_next: Optional[str] = None
    try:
        data = json.loads(body_txt) if body_txt else {}
        flow_token_next = data.get("flow_token")
    except Exception:
        flow_token_next = None
    success = status_code is not None and 200 <= status_code < 300 and not error_found
    return success, new_ct0, status_code, flow_token_next


def _begin_verification(session: Any, *, email: str, flow_token: str, ct0: str,
                        user_agent: str, transaction_id: Optional[str],
                        xpff_token: Optional[str], timeout: Optional[float]) -> Tuple[bool, Optional[str], Optional[int], Optional[str]]:
    url = "https://api.x.com/1.1/onboarding/begin_verification.json"
    headers = _shuffle_headers({
        "authorization": (
            "Bearer "
            "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs=1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
        ),
        "x-csrf-token": ct0,
        "accept-language": "en-US",
        "sec-ch-ua": '"Google Chrome";v="142", "Chromium";v="142", "Not A(Brand";v="24"',
        "sec-ch-ua-platform": '"Windows"',
        "sec-ch-ua-mobile": "?0",
        "x-twitter-client-language": "en",
        "x-twitter-active-user": "yes",
        "x-twitter-auth-type": "OAuth2Session",
        "user-agent": user_agent,
        "accept": "*/*",
        "origin": "https://x.com",
        "sec-fetch-site": "same-site",
        "sec-fetch-mode": "cors",
        "sec-fetch-dest": "empty",
        "referer": "https://x.com/",
        "accept-encoding": "gzip, deflate, br",
        "priority": "u=1, i",
        "content-type": "application/json",
    })
    if transaction_id:
        headers["x-client-transaction-id"] = transaction_id
    if xpff_token:
        headers["x-xp-forwarded-for"] = xpff_token

    payload = {
        "email": email,
        "flow_token": flow_token,
    }
    resp = _post_with_retry(
        session,
        url,
        headers=headers,
        json_payload=payload,
        timeout=timeout,
        label="begin_verification",
    )
    if resp is None:
        return False, None, None, None
    status_code = getattr(resp, "status_code", None)
    body_txt = _resolve_response_text(resp)
    _log_response("begin_verification", status_code, body_txt)
    error_found = _log_error_if_any("begin_verification", body_txt, status_code)
    new_ct0 = _extract_ct0_from_response(session, resp)
    flow_token_next: Optional[str] = None
    try:
        data = json.loads(body_txt) if body_txt else {}
        flow_token_next = data.get("flow_token")
    except Exception:
        flow_token_next = None
    success = status_code is not None and 200 <= status_code < 300 and not error_found
    return success, new_ct0, status_code, flow_token_next


def _submit_email_association(session: Any, *, email: str, code: str, flow_token: str,
                              ct0: str, user_agent: str, transaction_id: Optional[str],
                              xpff_token: Optional[str], timeout: Optional[float]) -> Tuple[bool, Optional[str], Optional[int]]:
    url = "https://api.x.com/1.1/onboarding/task.json"
    headers = _shuffle_headers({
        "authorization": (
            "Bearer "
            "AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs=1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA"
        ),
        "x-csrf-token": ct0,
        "accept-language": "en-US",
        "sec-ch-ua": '"Google Chrome";v="142", "Chromium";v="142", "Not A(Brand";v="24"',
        "sec-ch-ua-platform": '"Windows"',
        "sec-ch-ua-mobile": "?0",
        "x-twitter-client-language": "en",
        "x-twitter-active-user": "yes",
        "x-twitter-auth-type": "OAuth2Session",
        "user-agent": user_agent,
        "accept": "*/*",
        "origin": "https://x.com",
        "sec-fetch-site": "same-site",
        "sec-fetch-mode": "cors",
        "sec-fetch-dest": "empty",
        "referer": "https://x.com/",
        "accept-encoding": "gzip, deflate, br",
        "priority": "u=1, i",
        "content-type": "application/json",
    })
    if transaction_id:
        headers["x-client-transaction-id"] = transaction_id
    if xpff_token:
        headers["x-xp-forwarded-for"] = xpff_token

    payload = {
        "flow_token": flow_token,
        "subtask_inputs": [
            {
                "subtask_id": "EmailAssocEnterEmail",
                "enter_email": {
                    "setting_responses": [
                        {
                            "key": "email_discoverability_setting",
                            "response_data": {
                                "boolean_data": {"result": False}
                            }
                        }
                    ],
                    "email": email,
                    "link": "next_link"
                }
            },
            {
                "subtask_id": "EmailAssocVerifyEmail",
                "email_verification": {
                    "code": code,
                    "email": email,
                    "link": "next_link"
                }
            }
        ]
    }
    resp = _post_with_retry(
        session,
        url,
        headers=headers,
        json_payload=payload,
        timeout=timeout,
        label="EmailAssoc",
    )
    if resp is None:
        return False, None, None
    status_code = getattr(resp, "status_code", None)
    body_txt = _resolve_response_text(resp)
    _log_response("email_assoc", status_code, body_txt)
    error_found = _log_error_if_any("email_assoc", body_txt, status_code)
    new_ct0 = _extract_ct0_from_response(session, resp)
    success = status_code is not None and 200 <= status_code < 300 and not error_found
    return success, new_ct0, status_code


def _apply_ct0_update(session: Any, user: Any, ct0_value: Optional[str]) -> Optional[str]:
    if not ct0_value:
        return None
    try:
        session.cookies.set("ct0", ct0_value, domain=".x.com")
    except Exception:
        pass
    try:
        setattr(user, "ct0", ct0_value)
    except Exception:
        pass
    return ct0_value


def change_email_for_user(
    user: Any,
    *,
    timeout: Optional[float] = None,
    stop_event: Optional[threading.Event] = None,
) -> EmailChangeResult:
    """
    add_email flow:
    1) get flow_token with flow_name=add_email
    2) order email from the configured mail service
    3) send DeviceAssocEnterPassword subtask
    cookies ct0/auth_token are used; ct0 is updated in-memory if it changes.
    """
    try:
        cfg = config_manager.load_config()
        user_agent = _resolve_user_agent(cfg.get("user_agent"))
        request_timeout = float(cfg.get("request_timeout", 8.0) or 8.0)
        txid_timeout = float(cfg.get("txid_timeout", request_timeout) or request_timeout)
        mail_service = _resolve_mail_service(cfg)
        mail_wait_attempts, mail_wait_interval = _resolve_mail_wait_settings(cfg)
    except Exception as exc:
        LOGGER.error("Config could not be read: %s", exc)
        return EmailChangeResult(False, error="config_error")

    if mail_service == "anymessage" and not str(cfg.get("anymessage_api_key", "")).strip():
        LOGGER.error("AnyMessage API key is missing in config.json.")
        return EmailChangeResult(False, error="missing_anymessage_api_key")
    if mail_service == "zeus" and not str(cfg.get("zeus_api_key", "")).strip():
        LOGGER.error("Zeus API key is missing in config.json.")
        return EmailChangeResult(False, error="missing_zeus_api_key")

    try:
        session = _create_tls_session(user_agent)
    except Exception as exc:
        LOGGER.error("TLS session could not be created: %s", exc)
        return EmailChangeResult(False, error="tls_session_error")

    try:
        proxy_url = _normalize_proxy(cfg.get("proxy", ""))
        _apply_proxy_to_session(session, proxy_url)
    except Exception as exc:
        LOGGER.error("Proxy could not be applied: %s", exc)
        return EmailChangeResult(False, error="proxy_error")

    try:
        if hasattr(session, "cookies") and hasattr(session.cookies, "set"):
            session.cookies.set("auth_token", getattr(user, "auth_token", ""), domain=".x.com")
            session.cookies.set("ct0", getattr(user, "ct0", ""), domain=".x.com")
    except Exception:
        pass

    user_id = getattr(user, "id", None) or 0
    if _is_cancelled(stop_event):
        _log_step(user_id, "cancel", "Cancelled before start.", level="warning", color=Fore.YELLOW)
        return EmailChangeResult(False, error="cancelled")
    _log_step(user_id, "start", "Email change flow started.", color=Fore.CYAN)
    current_ct0 = getattr(user, "ct0", "") or ""
    password = getattr(user, "password", "") or ""

    txid_provider = _get_txid_provider(txid_timeout)
    try:
        tid_start = txid_provider.generate("POST", "/1.1/onboarding/task.json?flow_name=add_email")
    except TransactionIdError as exc:
        LOGGER.error("Transaction-id (start) could not be generated: %s", exc)
        tid_start = None

    _log_step(user_id, "start_flow", "add_email flow starting.", color=Fore.CYAN)
    flow_token, new_ct0, status_start, start_locked, start_subtasks = _start_add_email_flow(
        session=session,
        ct0=current_ct0,
        user_agent=user_agent,
        transaction_id=tid_start,
        timeout=timeout if timeout is not None else request_timeout,
    )
    updated = _apply_ct0_update(session, user, new_ct0)
    if updated:
        current_ct0 = updated
    if start_subtasks:
        _log_step(
            user_id,
            "start_flow",
            f"Start subtasks: {', '.join(start_subtasks)}",
            color=Fore.CYAN,
        )

    if start_locked:
        _log_step(user_id, "lock", "Account appears temporarily locked.", level="warning", color=Fore.YELLOW)
        return EmailChangeResult(False, ct0=current_ct0, error="account_locked", locked=True)

    if _is_cancelled(stop_event):
        _log_step(user_id, "cancel", "Cancelled after start flow.", level="warning", color=Fore.YELLOW)
        return EmailChangeResult(False, ct0=current_ct0, error="cancelled")

    if not (status_start and 200 <= status_start < 300 and flow_token):
        _log_step(
            user_id,
            "start_flow",
            f"flow_token not obtained or status failed (status={status_start}, flow_token={bool(flow_token)}).",
            level="warning",
            color=Fore.YELLOW,
        )
        return EmailChangeResult(False, ct0=current_ct0, error="start_flow_failed")
    _log_step(user_id, "start_flow", f"flow_token received (status={status_start}).", color=Fore.GREEN)

    guest_id = _extract_guest_id(session)
    xpff_token = ""
    try:
        if guest_id:
            xpff_token, _ = xpff_header_generator.generate(user_agent, guest_id)
    except Exception as exc:
        LOGGER.warning("XPFF could not be generated: %s", exc)

    first_subtask = start_subtasks[0] if start_subtasks else ""
    email_first = first_subtask == "EmailAssocEnterEmail"
    if not email_first and not password:
        _log_step(
            user_id,
            "password",
            "Password is empty; DeviceAssocEnterPassword cannot be sent.",
            level="error",
            color=Fore.RED,
        )
        return EmailChangeResult(False, ct0=current_ct0, error="missing_password")

    flow_token_pw = flow_token
    if not email_first:
        try:
            tid_pw = txid_provider.generate("POST", "/1.1/onboarding/task.json")
        except TransactionIdError as exc:
            LOGGER.error("Transaction-id (password) could not be generated: %s", exc)
            tid_pw = None

        _log_step(user_id, "password", "Password verification step sending.", color=Fore.CYAN)
        success, new_ct0_2, status_pw, flow_token_pw = _submit_add_email_password(
            session=session,
            ct0=current_ct0,
            user_agent=user_agent,
            transaction_id=tid_pw,
            flow_token=flow_token,
            password=password,
            xpff_token=xpff_token,
            timeout=timeout if timeout is not None else request_timeout,
        )
        updated = _apply_ct0_update(session, user, new_ct0_2)
        if updated:
            current_ct0 = updated

        if not success or not flow_token_pw:
            _log_step(
                user_id,
                "password",
                f"Password subtask failed or flow_token missing (status={status_pw}, flow_token={bool(flow_token_pw)}).",
                level="warning",
                color=Fore.YELLOW,
            )
            return EmailChangeResult(False, ct0=current_ct0, error="password_step_failed")
        _log_step(user_id, "password", f"Password step succeeded (status={status_pw}).", color=Fore.GREEN)

    if _is_cancelled(stop_event):
        _log_step(user_id, "cancel", "Cancelled after password step.", level="warning", color=Fore.YELLOW)
        return EmailChangeResult(False, ct0=current_ct0, error="cancelled")

    service_label_map = {"mailtm": "MailTM", "anymessage": "AnyMessage", "zeus": "Zeus"}
    service_label = service_label_map.get(mail_service, mail_service)
    if mail_service == "mailtm":
        _log_step(user_id, "order_email", "Ordering email from MailTM.", color=Fore.CYAN)
        mail_result = mailtm_service.order_email_with_retry()
    elif mail_service == "zeus":
        _log_step(user_id, "order_email", "Ordering email from Zeus.", color=Fore.CYAN)
        mail_result = zeus_service.order_email_with_retry()
    else:
        _log_step(user_id, "order_email", "Ordering email from AnyMessage.", color=Fore.CYAN)
        mail_result = anymessage_service.order_email_with_retry()
    if not mail_result.ok:
        _log_step(
            user_id,
            "order_email",
            f"{service_label} order failed: {mail_result.error or mail_result.text}",
            level="error",
            color=Fore.RED,
        )
        return EmailChangeResult(False, ct0=current_ct0, error="order_email_failed")
    new_email = mail_result.email or ""
    new_email_id = mail_result.email_id or ""
    api_key_anymsg = str(cfg.get("anymessage_api_key", "")).strip() if mail_service == "anymessage" else ""
    mailtm_account = None
    zeus_mailbox = None
    mailbox_password = ""
    if mail_service == "mailtm" and isinstance(mail_result.data, dict):
        mailtm_account = mail_result.data.get("account")
        mailbox_password = str(getattr(mailtm_account, "password", "") or "")
    if mail_service == "zeus" and isinstance(mail_result.data, dict):
        zeus_mailbox = mail_result.data.get("mailbox")
        if isinstance(zeus_mailbox, dict):
            mailbox_password = str(zeus_mailbox.get("password") or "")
    if mailbox_password:
        if len(mailbox_password) > 12:
            masked_secret = mailbox_password[:6] + "..." + mailbox_password[-4:]
        else:
            masked_secret = "***"
        LOGGER.info(
            "%s order ok; email=%s email_id=%s mail_secret=%s",
            service_label,
            new_email,
            new_email_id,
            masked_secret,
        )
    else:
        LOGGER.info("%s order ok; email=%s email_id=%s", service_label, new_email, new_email_id)
    if not new_email:
        LOGGER.error("%s order did not return email.", service_label)
        return EmailChangeResult(False, ct0=current_ct0, error="email_missing")

    if _is_cancelled(stop_event):
        _log_step(user_id, "cancel", "Cancelled after email order.", level="warning", color=Fore.YELLOW)
        return EmailChangeResult(False, ct0=current_ct0, error="cancelled")

    if email_first:
        try:
            tid_enter = txid_provider.generate("POST", "/1.1/onboarding/task.json")
        except TransactionIdError as exc:
            LOGGER.error("Transaction-id (email enter) could not be generated: %s", exc)
            tid_enter = None

        _log_step(user_id, "email_enter", "Email entry step sending.", color=Fore.CYAN)
        enter_ok, new_ct0_2, status_enter, flow_token_enter, enter_error_code, enter_error_message = _submit_email_enter(
            session=session,
            email=new_email,
            flow_token=flow_token,
            ct0=current_ct0,
            user_agent=user_agent,
            transaction_id=tid_enter,
            xpff_token=xpff_token,
            timeout=timeout if timeout is not None else request_timeout,
        )
        updated = _apply_ct0_update(session, user, new_ct0_2)
        if updated:
            current_ct0 = updated

        if not enter_ok or not flow_token_enter:
            if _requires_email_verify_input(enter_error_code, enter_error_message):
                _log_step(
                    user_id,
                    "email_enter",
                    "Flow requires EmailAssocVerifyEmail in the same task; continuing with combined email association path.",
                    level="warning",
                    color=Fore.YELLOW,
                )
                email_first = False
            else:
                _log_step(
                    user_id,
                    "email_enter",
                    f"Email enter subtask failed or flow_token missing (status={status_enter}, flow_token={bool(flow_token_enter)}).",
                    level="warning",
                    color=Fore.YELLOW,
                )
                return EmailChangeResult(False, ct0=current_ct0, error="email_enter_failed")
        else:
            _log_step(user_id, "email_enter", f"Email enter step succeeded (status={status_enter}).", color=Fore.GREEN)
            flow_token_pw = flow_token_enter

    try:
        tid_verify = txid_provider.generate("POST", "/1.1/onboarding/begin_verification.json")
    except TransactionIdError as exc:
        LOGGER.error("Transaction-id (begin_verification) could not be generated: %s", exc)
        tid_verify = None

    _log_step(user_id, "begin_verification", "Email verification starting.", color=Fore.CYAN)
    verify_ok, new_ct0_3, status_verify, flow_token_verify = _begin_verification(
        session=session,
        email=new_email,
        flow_token=flow_token_pw,
        ct0=current_ct0,
        user_agent=user_agent,
        transaction_id=tid_verify,
        xpff_token=xpff_token,
        timeout=timeout if timeout is not None else request_timeout,
    )
    updated = _apply_ct0_update(session, user, new_ct0_3)
    if updated:
        current_ct0 = updated

    if not verify_ok:
        _log_step(
            user_id,
            "begin_verification",
            f"begin_verification failed (status={status_verify}).",
            level="warning",
            color=Fore.YELLOW,
        )
        return EmailChangeResult(False, ct0=current_ct0, error="begin_verification_failed")
    if _is_cancelled(stop_event):
        _log_step(user_id, "cancel", "Cancelled after begin_verification.", level="warning", color=Fore.YELLOW)
        return EmailChangeResult(False, ct0=current_ct0, error="cancelled")
    if status_verify != 204:
        _log_step(
            user_id,
            "begin_verification",
            f"begin_verification returned unexpected status (status={status_verify}); email code may not arrive.",
            level="warning",
            color=Fore.YELLOW,
        )

    verification_code: Optional[str] = None
    if status_verify == 204:
        _log_step(
            user_id,
            "wait_email",
            f"Waiting for verification code via {service_label} (attempts={mail_wait_attempts}, interval={mail_wait_interval}s).",
            color=Fore.CYAN,
        )
        if mail_service == "anymessage" and api_key_anymsg and new_email_id:
            try:
                result = anymessage_service.wait_for_email(
                    api_key_anymsg,
                    new_email_id,
                    attempts=mail_wait_attempts,
                    interval_sec=mail_wait_interval,
                    stop_event=stop_event,
                )
                LOGGER.info(
                    "AnyMessage mail check result ok=%s code=%s attempts=%s",
                    result.ok,
                    result.code,
                    result.attempts,
                )
                if result.code:
                    LOGGER.info("AnyMessage verification code: %s", result.code)
                if result.ok and result.code:
                    verification_code = result.code
                    _log_step(user_id, "wait_email", "Verification code received.", color=Fore.GREEN)
                elif result.error == "cancelled":
                    _log_step(user_id, "wait_email", "Cancelled while waiting for email.", level="warning", color=Fore.YELLOW)
                    return EmailChangeResult(False, ct0=current_ct0, error="cancelled")
                else:
                    _log_step(
                        user_id,
                        "wait_email",
                        f"AnyMessage code not received; ok={result.ok} code={result.code}",
                        level="warning",
                        color=Fore.YELLOW,
                    )
                    return EmailChangeResult(False, ct0=current_ct0, error="email_code_missing")
            except Exception as exc:
                _log_step(user_id, "wait_email", f"AnyMessage mail read error: {exc}", level="error", color=Fore.RED)
                return EmailChangeResult(False, ct0=current_ct0, error="email_read_error")
        elif mail_service == "mailtm":
            if mailtm_account is None:
                _log_step(
                    user_id,
                    "wait_email",
                    "MailTM account missing; email cannot be read.",
                    level="error",
                    color=Fore.RED,
                )
                return EmailChangeResult(False, ct0=current_ct0, error="email_read_error")
            try:
                result = mailtm_service.wait_for_email(
                    mailtm_account,
                    attempts=mail_wait_attempts,
                    interval_sec=mail_wait_interval,
                    stop_event=stop_event,
                )
                LOGGER.info(
                    "MailTM mail check result ok=%s code=%s attempts=%s",
                    result.ok,
                    result.code,
                    result.attempts,
                )
                if result.code:
                    LOGGER.info("MailTM verification code: %s", result.code)
                if result.ok and result.code:
                    verification_code = result.code
                    _log_step(user_id, "wait_email", "Verification code received.", color=Fore.GREEN)
                elif result.error == "cancelled":
                    _log_step(user_id, "wait_email", "Cancelled while waiting for email.", level="warning", color=Fore.YELLOW)
                    return EmailChangeResult(False, ct0=current_ct0, error="cancelled")
                else:
                    _log_step(
                        user_id,
                        "wait_email",
                        f"MailTM code not received; ok={result.ok} code={result.code}",
                        level="warning",
                        color=Fore.YELLOW,
                    )
                    return EmailChangeResult(False, ct0=current_ct0, error="email_code_missing")
            except Exception as exc:
                _log_step(user_id, "wait_email", f"MailTM mail read error: {exc}", level="error", color=Fore.RED)
                return EmailChangeResult(False, ct0=current_ct0, error="email_read_error")
        elif mail_service == "zeus":
            if not isinstance(zeus_mailbox, dict):
                _log_step(
                    user_id,
                    "wait_email",
                    "Zeus mailbox credentials are missing; email cannot be read.",
                    level="error",
                    color=Fore.RED,
                )
                return EmailChangeResult(False, ct0=current_ct0, error="email_read_error")
            try:
                result = zeus_service.wait_for_email(
                    zeus_mailbox,
                    attempts=mail_wait_attempts,
                    interval_sec=mail_wait_interval,
                    stop_event=stop_event,
                )
                LOGGER.info(
                    "Zeus mail check result ok=%s code=%s attempts=%s",
                    result.ok,
                    result.code,
                    result.attempts,
                )
                if result.code:
                    LOGGER.info("Zeus verification code: %s", result.code)
                if result.ok and result.code:
                    verification_code = result.code
                    _log_step(user_id, "wait_email", "Verification code received.", color=Fore.GREEN)
                elif result.error == "cancelled":
                    _log_step(user_id, "wait_email", "Cancelled while waiting for email.", level="warning", color=Fore.YELLOW)
                    return EmailChangeResult(False, ct0=current_ct0, error="cancelled")
                else:
                    _log_step(
                        user_id,
                        "wait_email",
                        f"Zeus code not received; ok={result.ok} code={result.code}",
                        level="warning",
                        color=Fore.YELLOW,
                    )
                    return EmailChangeResult(False, ct0=current_ct0, error="email_code_missing")
            except Exception as exc:
                _log_step(user_id, "wait_email", f"Zeus mail read error: {exc}", level="error", color=Fore.RED)
                return EmailChangeResult(False, ct0=current_ct0, error="email_read_error")

    if not verification_code:
        _log_step(
            user_id,
            "wait_email",
            "Verification code not found; email assoc cannot be sent.",
            level="error",
            color=Fore.RED,
        )
        return EmailChangeResult(False, ct0=current_ct0, error="verification_code_missing")

    flow_token_email = flow_token_verify or flow_token_pw
    try:
        tid_email = txid_provider.generate("POST", "/1.1/onboarding/task.json")
    except TransactionIdError as exc:
        LOGGER.error("Transaction-id (email assoc) could not be generated: %s", exc)
        tid_email = None

    if email_first:
        _log_step(user_id, "email_verify", "Email verification step sending.", color=Fore.CYAN)
        assoc_ok, new_ct0_4, status_assoc, flow_token_verify_next = _submit_email_verify(
            session=session,
            email=new_email,
            code=verification_code,
            flow_token=flow_token_email,
            ct0=current_ct0,
            user_agent=user_agent,
            transaction_id=tid_email,
            xpff_token=xpff_token,
            timeout=timeout if timeout is not None else request_timeout,
        )
        if flow_token_verify_next:
            flow_token_email = flow_token_verify_next
    else:
        _log_step(user_id, "email_assoc", "EmailAssoc step sending.", color=Fore.CYAN)
        assoc_ok, new_ct0_4, status_assoc = _submit_email_association(
            session=session,
            email=new_email,
            code=verification_code,
            flow_token=flow_token_email,
            ct0=current_ct0,
            user_agent=user_agent,
            transaction_id=tid_email,
            xpff_token=xpff_token,
            timeout=timeout if timeout is not None else request_timeout,
        )
    updated = _apply_ct0_update(session, user, new_ct0_4)
    if updated:
        current_ct0 = updated

    if not assoc_ok:
        _log_step(
            user_id,
            "email_assoc" if not email_first else "email_verify",
            f"EmailAssoc request failed (status={status_assoc}).",
            level="warning",
            color=Fore.YELLOW,
        )
        return EmailChangeResult(False, ct0=current_ct0, error="email_assoc_failed")
    _log_step(
        user_id,
        "email_assoc" if not email_first else "email_verify",
        f"EmailAssoc succeeded (status={status_assoc}).",
        color=Fore.GREEN,
    )

    return EmailChangeResult(
        True,
        email=new_email,
        email_id=new_email_id,
        mail_password=mailbox_password,
        ct0=current_ct0,
    )


__all__ = ["EmailChangeResult", "change_email_for_user"]
