from __future__ import annotations

import base64
import json
import os
import re
import socket
from dataclasses import dataclass
from typing import Any, Callable
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlsplit
from urllib.request import Request, urlopen


ACTION_WOOCOMMERCE_GET_ORDER = "woocommerce.get_order"
SUPPORTED_ACTIONS = {ACTION_WOOCOMMERCE_GET_ORDER}


class IntegrationError(RuntimeError):
    def __init__(self, code: str, public_message: str, *, status_code: int = 502):
        self.code = code
        self.public_message = public_message
        self.status_code = status_code
        super().__init__(public_message)


@dataclass(frozen=True)
class WooCommerceConfig:
    base_url: str
    consumer_key: str
    consumer_secret: str
    timeout: int = 10

    @classmethod
    def from_env(cls) -> "WooCommerceConfig":
        timeout_text = os.getenv("ARCO_WC_TIMEOUT", "10").strip()
        try:
            timeout = int(timeout_text)
        except ValueError:
            timeout = 10
        return cls(
            base_url=os.getenv("ARCO_WC_BASE_URL", "https://arcopet.com").strip().rstrip("/"),
            consumer_key=os.getenv("ARCO_WC_CONSUMER_KEY", "").strip(),
            consumer_secret=os.getenv("ARCO_WC_CONSUMER_SECRET", "").strip(),
            timeout=max(2, min(30, timeout)),
        )

    @property
    def configured(self) -> bool:
        return bool(self.base_url and self.consumer_key and self.consumer_secret)

    def validate(self) -> None:
        if not self.configured:
            raise IntegrationError(
                "not_configured",
                "اتصال WooCommerce هنوز تنظیم نشده است.",
                status_code=503,
            )
        parsed = urlsplit(self.base_url)
        if parsed.scheme != "https" or not parsed.netloc or parsed.username or parsed.password:
            raise IntegrationError(
                "invalid_configuration",
                "آدرس WooCommerce باید یک آدرس معتبر HTTPS باشد.",
                status_code=500,
            )


STATUS_LABELS = {
    "pending": "در انتظار پرداخت",
    "processing": "در حال پردازش",
    "on-hold": "در انتظار بررسی",
    "completed": "تکمیل‌شده",
    "cancelled": "لغوشده",
    "refunded": "بازپرداخت‌شده",
    "failed": "ناموفق",
    "custom-status": "تحویل پیک",
    "custom-done": "تحویل‌شده",
    "custom-post": "تحویل پست",
    "ronadprocess": "در حال پردازش در انبار",
    "ronadpack": "در حال بسته‌بندی",
    "ronadpeyk": "تحویل پیک",
    "ronadsend": "ارسال‌شده",
}

RONAD_STATUS_LABELS = {
    "DELIVERED": "تحویل‌شده",
    "DELIVERED_TO_POST": "تحویل پست",
    "DELIVERED_TO_COURIER": "تحویل پیک",
    "NOT_DELIVERED": "هنوز تحویل نشده",
}

PERSIAN_DIGITS = str.maketrans("۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩", "01234567890123456789")


def normalize_iran_phone(value: Any) -> str:
    digits = re.sub(r"\D+", "", str(value or "").translate(PERSIAN_DIGITS))
    if digits.startswith("0098"):
        digits = digits[2:]
    if digits.startswith("98") and len(digits) == 12:
        digits = "0" + digits[2:]
    elif digits.startswith("9") and len(digits) == 10:
        digits = "0" + digits
    return digits


def normalize_order_id(value: Any) -> int:
    if isinstance(value, float) and value.is_integer():
        value = int(value)
    text = str(value or "").translate(PERSIAN_DIGITS).strip()
    if not re.fullmatch(r"[0-9]{1,18}", text):
        raise IntegrationError("invalid_input", "شماره سفارش معتبر نیست.", status_code=400)
    order_id = int(text)
    if order_id < 1:
        raise IntegrationError("invalid_input", "شماره سفارش معتبر نیست.", status_code=400)
    return order_id


def meta_value(order: dict[str, Any], key: str) -> str:
    for item in order.get("meta_data", []):
        if isinstance(item, dict) and item.get("key") == key:
            value = item.get("value")
            if isinstance(value, (str, int, float)):
                return str(value).strip()
    return ""


def safe_order_result(order: dict[str, Any]) -> dict[str, Any]:
    status = str(order.get("status", "")).strip()
    status_label = STATUS_LABELS.get(status, status.replace("-", " ") or "نامشخص")
    delivery_date = meta_value(order, "_delivery_date") or "ثبت نشده"
    delivery_time = meta_value(order, "_delivery_time") or "ثبت نشده"
    tracking_number = meta_value(order, "post_track_number") or "هنوز صادر نشده"
    ronad_status = meta_value(order, "status_in_ronad")
    ronad_label = RONAD_STATUS_LABELS.get(ronad_status, "")
    if ronad_label:
        status_label = ronad_label
    number = str(order.get("number") or order.get("id") or "—")
    summary_lines = [
        f"وضعیت سفارش #{number}: {status_label}",
        f"تاریخ تحویل: {delivery_date}",
        f"بازه تحویل: {delivery_time}",
    ]
    if tracking_number != "هنوز صادر نشده":
        summary_lines.append(f"کد رهگیری: {tracking_number}")
    return {
        "number": number,
        "status": status,
        "status_label": status_label,
        "delivery_date": delivery_date,
        "delivery_time": delivery_time,
        "tracking_number": tracking_number,
        "summary": "\n".join(summary_lines),
    }


Transport = Callable[[Request, int], Any]


class WooCommerceIntegration:
    def __init__(self, config: WooCommerceConfig | None = None, transport: Transport | None = None):
        self.config = config or WooCommerceConfig.from_env()
        self.transport = transport or (lambda request, timeout: urlopen(request, timeout=timeout))

    def public_status(self) -> dict[str, Any]:
        return {
            "configured": self.config.configured,
            "base_url": self.config.base_url,
            "timeout": self.config.timeout,
            "api_version": "wc/v3",
            "permission": "read_only",
            "verification": "order_id_and_phone",
        }

    def _request(self, endpoint: str, with_headers: bool = False) -> Any:
        self.config.validate()
        credentials = f"{self.config.consumer_key}:{self.config.consumer_secret}".encode("utf-8")
        authorization = base64.b64encode(credentials).decode("ascii")
        request = Request(
            f"{self.config.base_url}/wp-json/wc/v3/{endpoint.lstrip('/')}",
            headers={
                "Accept": "application/json",
                "Authorization": f"Basic {authorization}",
                "User-Agent": "ArcopetBot/3.0",
            },
            method="GET",
        )
        try:
            with self.transport(request, self.config.timeout) as response:
                raw = response.read(2_000_001)
                total_pages = response.headers.get("X-WP-TotalPages") if with_headers and hasattr(response, "headers") else None
        except HTTPError as exc:
            if exc.code == 404:
                if endpoint.startswith("orders/"):
                    raise IntegrationError("order_not_found", "اطلاعات سفارش مطابقت ندارد.", status_code=404) from exc
                raise IntegrationError("taxonomy_not_found", "مسیر اصطلاحات در WooCommerce پیدا نشد.", status_code=404) from exc
            if exc.code in {401, 403}:
                raise IntegrationError("authentication_failed", "دسترسی WooCommerce معتبر نیست.") from exc
            raise IntegrationError("upstream_error", "سرویس فروشگاه موقتاً پاسخ‌گو نیست.") from exc
        except (URLError, TimeoutError, socket.timeout, OSError) as exc:
            raise IntegrationError("connection_failed", "ارتباط با فروشگاه برقرار نشد.") from exc
        if len(raw) > 2_000_000:
            raise IntegrationError("invalid_response", "پاسخ فروشگاه بیش از حد مجاز است.")
        try:
            payload = json.loads(raw.decode("utf-8"))
            return (payload, total_pages) if with_headers else payload
        except (UnicodeDecodeError, json.JSONDecodeError) as exc:
            raise IntegrationError("invalid_response", "پاسخ فروشگاه قابل خواندن نیست.") from exc

    def test_connection(self) -> dict[str, Any]:
        payload = self._request("orders?per_page=1&_fields=id")
        if not isinstance(payload, list):
            raise IntegrationError("invalid_response", "پاسخ WooCommerce معتبر نیست.")
        return {"ok": True, "message": "اتصال Read-only WooCommerce برقرار است."}

    def get_order(self, order_id: Any, phone: Any) -> dict[str, Any]:
        normalized_order_id = normalize_order_id(order_id)
        supplied_phone = normalize_iran_phone(phone)
        if not re.fullmatch(r"09[0-9]{9}", supplied_phone):
            raise IntegrationError("invalid_input", "شماره موبایل معتبر نیست.", status_code=400)
        order = self._request(f"orders/{quote(str(normalized_order_id), safe='')}")
        if not isinstance(order, dict):
            raise IntegrationError("invalid_response", "پاسخ سفارش معتبر نیست.")
        billing = order.get("billing") if isinstance(order.get("billing"), dict) else {}
        order_phone = normalize_iran_phone(billing.get("phone"))
        if not order_phone or not hmac_compare(order_phone, supplied_phone):
            raise IntegrationError("order_not_found", "اطلاعات سفارش مطابقت ندارد.", status_code=404)
        return safe_order_result(order)


def hmac_compare(left: str, right: str) -> bool:
    # Constant-time comparison avoids leaking how much of the supplied phone matched.
    import hmac

    return hmac.compare_digest(left.encode("utf-8"), right.encode("utf-8"))


def execute_integration_action(action: str, inputs: dict[str, Any]) -> dict[str, Any]:
    if action not in SUPPORTED_ACTIONS:
        return {
            "ok": False,
            "error": {"code": "unsupported_action", "message": "Action مجاز نیست."},
        }
    try:
        result = WooCommerceIntegration().get_order(inputs.get("order_id"), inputs.get("phone"))
        return {"ok": True, "data": result}
    except IntegrationError as exc:
        return {"ok": False, "error": {"code": exc.code, "message": exc.public_message}}
