"""
AnyMessage e-posta servisi ile siparis ve stok islemleri icin sade yardimcilar.
Config bilgilerini config_manager.load_config() uzerinden okur.
"""
from __future__ import annotations

import json
import logging
import threading
import time
from dataclasses import dataclass
from typing import Any, Dict, Optional, Tuple

import requests
import re

import config_manager

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

BASE_URL = "https://api.anymessage.shop"
ORDER_ENDPOINT = f"{BASE_URL}/email/order"
QUANTITY_ENDPOINT = f"{BASE_URL}/email/quantity"
GET_MESSAGE_ENDPOINT = f"{BASE_URL}/email/getmessage"
CODE_REGEX = re.compile(r"(?<!\\d)(\\d{6})(?!\\d)")


@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 _extract_email_fields(data: Optional[Dict[str, Any]]) -> Tuple[Optional[str], Optional[str]]:
    if not isinstance(data, dict):
        return None, None
    email = data.get("email") or data.get("mail") or data.get("value")
    email_id = data.get("id") or data.get("email_id") or data.get("order_id")
    if isinstance(email, dict):
        email = email.get("email") or email.get("value")
    if email is not None:
        email = str(email)
    if email_id is not None:
        email_id = str(email_id)
    return email, email_id


def _load_anymessage_settings() -> Tuple[str, str]:
    cfg = config_manager.load_config()
    api_key = str(cfg.get("anymessage_api_key") or "").strip()
    domain = str(cfg.get("anymessage_domain") or "gmail.com").strip() or "gmail.com"
    return api_key, domain


def order_email_with_config() -> EmailOrderResult:
    """
    Config'teki api_key/domain ile AnyMessage uzerinden e-posta siparisi olusturur.
    """
    api_key, domain = _load_anymessage_settings()
    if not api_key:
        return EmailOrderResult(False, 0, "Missing AnyMessage API key", None, "missing_api_key")

    url = f"{ORDER_ENDPOINT}?token={api_key}&site=x.com&domain={domain}&soft_id=3219"
    try:
        resp = requests.get(url, timeout=40)
    except Exception as exc:
        return EmailOrderResult(False, 0, str(exc), None, str(exc))

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

    ok = False
    error_val: Optional[str] = None
    email_addr: Optional[str] = None
    email_id: Optional[str] = None

    if isinstance(data, dict):
        status = str(data.get("status", "")).lower()
        ok = resp.status_code == 200 and status == "success"
        email_addr, email_id = _extract_email_fields(data.get("data") or data)
        if not ok:
            for key in ("message", "error", "detail", "description", "status_message", "statusMessage", "msg", "value"):
                val = data.get(key)
                if isinstance(val, (str, int, float)):
                    error_val = str(val)
                    break
    else:
        ok = resp.status_code == 200

    if not ok and not error_val:
        preview = (text or "").strip()
        if preview:
            preview = " ".join(preview.split())
            if len(preview) > 200:
                preview = preview[:197] + "..."
            error_val = preview

    return EmailOrderResult(ok, resp.status_code, text, data, error_val, email=email_addr, email_id=email_id)


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


def order_email_with_retry(max_attempts: int = 180, delay_seconds: float = 3.0) -> EmailOrderResult:
    """
    AnyMessage uzerinden mail siparisini belirtilen deneme sayisi ve aralikla tekrar dener.
    'no emails' hatasinda bekleyip tekrar dener; baska bir hata gelirse hemen dondurur.
    """
    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

        text_lower = (result.text or "").lower()
        value_lower = ""
        status_lower = ""
        if isinstance(result.data, dict):
            value_lower = str(result.data.get("value", "")).lower()
            status_lower = str(result.data.get("status", "")).lower()

        no_email = ("no emails" in text_lower) or (value_lower == "no emails")
        if not no_email:
            return result

        LOGGER.warning("AnyMessage 'no emails' response (attempt %s/%s)", attempt, max_attempts)
        if attempt >= max_attempts:
            result.error = result.error or "no_emails_exhausted"
            return result
        try:
            time.sleep(max(delay, 0))
        except Exception:
            pass

    # Fallback: hic sonuc yoksa genel hata
    return last_result or EmailOrderResult(False, 0, "no result", None, "no_result")


def _extract_verification_code(mail_data: Optional[Dict[str, Any]], raw_text: str) -> Optional[str]:
    if isinstance(mail_data, dict):
        value = str(mail_data.get("value", "")).strip()
        if value.isdigit() and len(value) == 6:
            return value
        message = mail_data.get("message", "")
        if isinstance(message, str):
            match = CODE_REGEX.search(message)
            if match:
                return match.group(1)
    if isinstance(raw_text, str):
        match = CODE_REGEX.search(raw_text)
        if match:
            return match.group(1)
    return None


def wait_for_email(
    api_key: str,
    email_id: str,
    *,
    attempts: int = 180,
    interval_sec: float = 3.0,
    stop_event: Optional[threading.Event] = None,
) -> MailCheckResult:
    """AnyMessage uzerinde belirtilen email_id icin mail bekler."""
    if attempts <= 0:
        attempts = 1
    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("AnyMessage wait cancelled after %s attempts.", attempt - 1)
            return MailCheckResult(False, 0, "cancelled", None, attempt - 1, "cancelled")
        try:
            resp = requests.get(
                GET_MESSAGE_ENDPOINT,
                params={"token": api_key, "id": email_id, "preview": 0},
                timeout=30,
            )
            last_text = resp.text
            try:
                last_data = resp.json()
            except Exception:
                last_data = None

            status_code = getattr(resp, "status_code", None) or 0
            payload_status = str((last_data or {}).get("status", "")).lower()
            LOGGER.info(
                "AnyMessage wait attempt %s/%s: status=%s payload_status=%s",
                attempt,
                attempts,
                status_code,
                payload_status or "-",
            )
            if status_code == 200 and payload_status == "success":
                code = _extract_verification_code(last_data, last_text)
                LOGGER.info(
                    "AnyMessage payload success; code_found=%s",
                    bool(code),
                )
                return MailCheckResult(True, status_code, last_text, last_data, attempt, None, code)
        except Exception as exc:
            last_text = str(exc)
            last_data = None
            LOGGER.warning("AnyMessage 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")
