from __future__ import annotations

from typing import Any, Dict

from db.master_taxonomy_registry import list_brands, list_collections
from magento.magento_api import MagentoRestClient
from magento.oauth_client import MagentoOAuthClient, build_magento_oauth_kwargs

# Interactive API must not use the Magento deploy-recovery loop (5m → 10m → 30m).
_SYNC_TIMEOUT_SECONDS = 180.0
_FETCH_TIMEOUT_SECONDS = 60.0


def build_brand_registry_payload(session) -> list[dict[str, Any]]:
    brands = list_brands(session, limit=500, active_only=None)
    payload: list[dict[str, Any]] = []
    for index, brand in enumerate(brands):
        brand_id = int(brand.get("id") or 0)
        if brand_id <= 0:
            continue

        collections = list_collections(session, brand_id=brand_id, limit=1000)
        payload.append(
            {
                "code": str(brand.get("code") or "").strip(),
                "name": str(brand.get("name") or "").strip(),
                "slug": str(brand.get("code") or "").strip() or str(brand.get("name") or "").strip(),
                "source_brand_id": brand_id,
                "sort_order": index,
                "is_active": bool(brand.get("is_active", True)),
                "image_url": str(brand.get("image_url") or "").strip() or None,
                "description": str(brand.get("description") or "").strip() or None,
                "collections": [
                    {
                        "path_slug": str(row.get("path_slug") or "").strip(),
                        "name": str(row.get("name") or "").strip(),
                        "source_registry_id": int(row.get("id") or 0) or None,
                        "position": collection_index,
                        "is_active": bool(row.get("is_active", True)),
                    }
                    for collection_index, row in enumerate(collections)
                    if str(row.get("path_slug") or "").strip()
                ],
            }
        )
    return payload


def _magento_api(connection: Dict[str, Any], *, timeout: float) -> MagentoRestClient:
    kwargs = build_magento_oauth_kwargs(connection, timeout=timeout)
    kwargs["max_recovery_rounds"] = 1
    return MagentoRestClient(MagentoOAuthClient(**kwargs))


def sync_brand_registry_for_connection(session, connection: Dict[str, Any], *, replace_existing: bool = True) -> Dict[str, Any]:
    api = _magento_api(connection, timeout=_SYNC_TIMEOUT_SECONDS)
    brands = build_brand_registry_payload(session)
    status, body, err = api.sync_brand_registry(brands, replace_existing=replace_existing)
    return {
        "status": status,
        "replace_existing": replace_existing,
        "brands_sent": len(brands),
        "collections_sent": sum(len(item.get("collections") or []) for item in brands),
        "result": body,
        "error": err,
        "ok": status in (200, 201, 202),
    }


def fetch_brand_registry_for_connection(connection: Dict[str, Any]) -> Dict[str, Any]:
    api = _magento_api(connection, timeout=_FETCH_TIMEOUT_SECONDS)
    status, body, err = api.get_brand_registry()
    return {
        "status": status,
        "result": body,
        "error": err,
        "ok": status == 200,
    }
