"""
Canifa API Service
Xử lý các logic liên quan đến API của Canifa (Magento)
"""

import hashlib
import json
import logging
from typing import Any

import httpx

logger = logging.getLogger(__name__)

CANIFA_CUSTOMER_API = "https://canifa.com/v1/magento/customer"

# ⚡ Auth Token Cache: TTL 1 tiếng — tránh gọi canifa.com mỗi request
AUTH_CACHE_TTL = 3600  # 1 hour
AUTH_CACHE_PREFIX = "auth_token:"

_http_client: httpx.AsyncClient | None = None


def _get_http_client() -> httpx.AsyncClient:
    global _http_client
    if _http_client is None:
        _http_client = httpx.AsyncClient(timeout=10.0)
    return _http_client


async def close_http_client() -> None:
    global _http_client
    if _http_client is not None:
        await _http_client.aclose()
        _http_client = None

CANIFA_QUERY_BODY = [
    {
        "customer": "customer-custom-query",
        "metadata": {
            "fields": "\n customer {\n gender\n customer_id\n phone_number\n date_of_birth\n default_billing\n default_shipping\n email\n firstname\n is_subscribed\n lastname\n middlename\n prefix\n suffix\n taxvat\n addresses {\n city\n country_code\n default_billing\n default_shipping\n extension_attributes {\n attribute_code\n value\n }\n custom_attributes {\n attribute_code\n value\n }\n firstname\n id\n lastname\n postcode\n prefix\n region {\n region_code\n region_id\n region\n }\n street\n suffix\n telephone\n vat_id\n }\n is_subscribed\n }\n "
        },
    },
    {},
]


async def _get_cached_auth(token: str) -> dict | None:
    """Check Redis cache for verified token."""
    try:
        from common.cache import redis_cache

        client = redis_cache.get_client()
        if not client:
            return None

        token_hash = hashlib.md5(token.encode()).hexdigest()
        key = f"{AUTH_CACHE_PREFIX}{token_hash}"
        cached = await client.get(key)
        if cached:
            logger.info("⚡ Auth token cache HIT — skipping Canifa API call")
            return json.loads(cached)
    except Exception as e:
        logger.warning(f"Auth cache read error: {e}")
    return None


async def _set_cached_auth(token: str, data: dict) -> None:
    """Store verified token result in Redis."""
    try:
        from common.cache import redis_cache

        client = redis_cache.get_client()
        if not client:
            return

        token_hash = hashlib.md5(token.encode()).hexdigest()
        key = f"{AUTH_CACHE_PREFIX}{token_hash}"
        await client.setex(key, AUTH_CACHE_TTL, json.dumps(data, ensure_ascii=False))
        logger.info(f"💾 Auth token cached (TTL: {AUTH_CACHE_TTL}s)")
    except Exception as e:
        logger.warning(f"Auth cache write error: {e}")


async def verify_canifa_token(token: str) -> dict[str, Any] | None:
    """
    Verify token với API Canifa (Magento) — có Redis cache.
    Lần đầu gọi API (~200-500ms), các lần sau hit cache (~2ms).

    Args:
        token: Giá trị của cookie vsf-customer (lấy từ Header Authorization)

    Returns:
        Dict info user hoặc None nếu lỗi
    """
    if not token:
        return None

    # ⚡ Check cache first
    cached_data = await _get_cached_auth(token)
    if cached_data is not None:
        return cached_data

    # Cache miss → call Canifa API
    headers = {
        "accept": "application/json, text/plain, */*",
        "content-type": "application/json",
        "Cookie": f"vsf-customer={token}",
    }

    try:
        client = _get_http_client()
        response = await client.post(CANIFA_CUSTOMER_API, json=CANIFA_QUERY_BODY, headers=headers)

        if response.status_code == 200:
            data = response.json()
            logger.debug(f"Canifa API Raw Response: {data}")

            if isinstance(data, dict):
                # ⚡ Cache successful auth result
                await _set_cached_auth(token, data)
                return data

            return data

        logger.warning(f"Canifa API Failed: {response.status_code} - {response.text}")
        return None

    except Exception as e:
        logger.error(f"Error calling Canifa API: {e}")
        return None


async def extract_user_id_from_canifa_response(data: Any) -> str | None:
    """
    Bóc customer_id từ response data của Canifa.
    """
    if not data:
        return None

    try:
        # Dự phòng các format data trả về khác nhau
        customer = None

        # Format 1: data['customer']
        if isinstance(data, dict):
            customer = data.get("customer") or data.get("data", {}).get("customer")

        # Format 2: data là list (nếu query batch)
        elif isinstance(data, list) and len(data) > 0:
            item = data[0]
            if isinstance(item, dict):
                customer = item.get("result", {}).get("customer") or item.get("data", {}).get("customer")

        if customer and isinstance(customer, dict):
            user_id = customer.get("customer_id") or customer.get("id")
            if user_id:
                return str(user_id)

        return None

    except Exception as e:
        logger.error(f"Error parsing user_id from Canifa response: {e}")
        return None
