"""
MailTM service helpers for ordering temp email and waiting for messages.
"""
from __future__ import annotations

import logging
import threading
import os
import random
import re
import string
import time
from dataclasses import dataclass
from typing import Any, Dict, Optional

import config_manager

LOGGER = logging.getLogger("x_email_changer.mailtm")
CODE_REGEX = re.compile(r"(?<!\d)(\d{6})(?!\d)")
_PROXY_CACHE = threading.local()


@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


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:
        token = "".join(random.choice(string.ascii_letters + string.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_env(proxy_url: str) -> None:
    os.environ["HTTP_PROXY"] = proxy_url
    os.environ["HTTPS_PROXY"] = proxy_url
    os.environ["http_proxy"] = proxy_url
    os.environ["https_proxy"] = proxy_url


def _ensure_proxy_from_config() -> Optional[str]:
    cfg = config_manager.load_config()
    if not cfg.get("mailtm_use_proxy"):
        return None
    raw_proxy = str(cfg.get("proxy") or "").strip()
    proxy_url = getattr(_PROXY_CACHE, "value", None)
    if not proxy_url:
        proxy_url = _normalize_proxy(raw_proxy)
        _PROXY_CACHE.value = proxy_url
    _apply_proxy_env(proxy_url)
    return proxy_url


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 _extract_code_from_message(message: Any) -> Optional[str]:
    candidates = [
        getattr(message, "text", ""),
        getattr(message, "intro", ""),
        getattr(message, "subject", ""),
    ]
    html = getattr(message, "html", None)
    if isinstance(html, list):
        candidates.extend(html)
    elif isinstance(html, str):
        candidates.append(html)
    for item in candidates:
        code = _extract_code_from_text(str(item or ""))
        if code:
            return code
    return None


def _extract_message_text(message: Any) -> str:
    for attr in ("text", "intro", "subject"):
        value = getattr(message, attr, "")
        if value:
            return str(value)
    return ""


def order_email_with_config() -> EmailOrderResult:
    """
    Creates a new MailTM account and returns the email address.
    """
    try:
        _ensure_proxy_from_config()
    except Exception as exc:
        return EmailOrderResult(False, 0, str(exc), None, "proxy_error")

    try:
        from pymailtm import MailTm
    except Exception as exc:
        return EmailOrderResult(False, 0, str(exc), None, "pymailtm_not_available")

    try:
        client = MailTm()
        account = client.get_account()
    except Exception as exc:
        return EmailOrderResult(False, 0, str(exc), None, str(exc))

    email = getattr(account, "address", "") or ""
    email_id = getattr(account, "id_", "") or ""
    if not email:
        return EmailOrderResult(False, 0, "MailTM account missing email address", None, "email_missing")

    return EmailOrderResult(True, 201, "ok", {"account": account}, None, str(email), str(email_id))


def order_email_with_retry(max_attempts: int = 5, delay_seconds: float = 2.0) -> EmailOrderResult:
    if max_attempts <= 0:
        max_attempts = 1
    delay = delay_seconds if delay_seconds is not None else 2.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
        LOGGER.warning("MailTM order failed (attempt %s/%s): %s", attempt, max_attempts, result.error or result.text)
        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 wait_for_email(
    account: Any,
    *,
    attempts: int = 180,
    interval_sec: float = 3.0,
    stop_event: Optional[threading.Event] = None,
) -> MailCheckResult:
    """Wait for a MailTM message and extract a 6-digit verification code."""
    if account is None:
        return MailCheckResult(False, 0, "missing account", None, 0, "missing_account")
    if attempts <= 0:
        attempts = 1

    known_ids = set()

    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("MailTM wait cancelled after %s attempts.", attempt - 1)
            return MailCheckResult(False, 0, "cancelled", None, attempt - 1, "cancelled")
        try:
            messages = account.get_messages() or []
            LOGGER.info("MailTM wait attempt %s/%s: messages=%s", attempt, attempts, len(messages))
            for msg in messages:
                msg_id = getattr(msg, "id_", None) or getattr(msg, "id", None)
                msg_id_str = str(msg_id) if msg_id is not None else ""
                if msg_id_str and msg_id_str in known_ids:
                    continue
                if msg_id_str:
                    known_ids.add(msg_id_str)
                code = _extract_code_from_message(msg)
                last_text = _extract_message_text(msg)
                last_data = {
                    "message_id": msg_id_str,
                    "subject": getattr(msg, "subject", ""),
                }
                if msg_id_str or last_text:
                    LOGGER.info(
                        "MailTM message seen id=%s subject=%s has_code=%s",
                        msg_id_str or "-",
                        getattr(msg, "subject", "") or "-",
                        bool(code),
                    )
                if code:
                    return MailCheckResult(True, 200, last_text, last_data, attempt, None, code)
        except Exception as exc:
            last_text = str(exc)
            last_data = None
            LOGGER.warning("MailTM wait error (attempt %s/%s): %s", attempt, attempts, exc)
        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"]
