"""Standalone, API-key-bound multi-tenant MCP gateway for the OmniStore catalogue API."""
from __future__ import annotations

import asyncio
import base64
import binascii
import contextvars
import hashlib
import hmac
import json
import logging
import math
import os
import re
import time
from contextlib import asynccontextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Literal
from urllib.parse import quote

import httpx
from mcp.server.fastmcp import FastMCP
from starlette.applications import Starlette
from starlette.responses import JSONResponse

logger = logging.getLogger("mcp.product_catalog")


def _load_env_file() -> None:
    """Load the adjacent deployment env file when the process manager omits it."""
    configured_path = os.environ.get("MCP_ENV_FILE")
    env_path = Path(configured_path) if configured_path else Path(__file__).resolve().parent.parent / "sme-omnistore-mcp.env"
    if not env_path.is_file():
        return
    for line in env_path.read_text(encoding="utf-8").splitlines():
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        if line.startswith("export "):
            line = line[7:].lstrip()
        key, separator, value = line.partition("=")
        if not separator or not key.strip():
            continue
        key = key.strip()
        value = value.strip()
        if len(value) >= 2 and value[0] == value[-1] and value[0] in "\"'":
            value = value[1:-1]
        os.environ.setdefault(key, value)


_load_env_file()


@dataclass(frozen=True)
class TenantConfig:
    name: str
    api_key_sha256: str
    tenant_id: int
    user_id: int
    backend_url: str
    email: str
    password: str
    store_domain: str | None
    token: str | None = None  # 用户令牌模式：原样转发给后端，不登录、不存密码


USER_TOKEN_PREFIX = "omcp_"

_INSTRUCTIONS = ('OmniStore back-office tools for the single tenant bound to this MCP key or token. Before statistics, '
 'sales, POS, inventory or catalogue work, call usage_guide(topic="index"), then the relevant workflow and '
 'reference topic. Use only registered tools and endpoint enums; never substitute arbitrary HTTP, SQL or '
 'unexposed POS/payment APIs. Reads, immediate catalogue/configuration writes, draft documents, and real '
 'inventory posting have different effects. Only perform writes within the user-authorized scope after '
 'resolving exact tenant-bound IDs and quantities. post_inventory_adjustment changes real stock; '
 'cancel_inventory_adjustment cancels drafts; set_product_stock only works without ledger takeover and '
 'variants. Read the latest price_rules_version before full rule replacement. Read all required pages; do '
 'not infer time order from order numbers. State date basis, timezone, currency, source and completeness in '
 'reports. Missing cost fields are not zero. Write timeouts require readback before retry; use supported '
 'stable idempotency keys. Do not reveal credentials or unrelated customer data.')


def _tenant_configs_from_environment() -> list[TenantConfig]:
    """Load a hash-keyed tenant registry, or adapt the legacy single-tenant env vars."""
    registry_path = os.environ.get("MCP_TENANTS_FILE")
    shared_backend_url = os.environ.get("MCP_BACKEND_URL", "").rstrip("/")
    rows: list[dict[str, Any]]
    if registry_path:
        path = Path(registry_path).expanduser()
        try:
            registry_data = json.loads(path.read_text(encoding="utf-8"))
        except (OSError, json.JSONDecodeError) as exc:
            raise RuntimeError(f"Could not load MCP tenant registry: {path}") from exc
        if not isinstance(registry_data, dict):
            raise RuntimeError("MCP tenant registry root must be a JSON object")
        rows = registry_data.get("tenants", [])
        if not isinstance(rows, list) or not rows:
            raise RuntimeError("MCP_TENANTS_FILE must contain a non-empty tenants array")
    elif not os.environ.get("MCP_API_KEY"):
        # 只用用户令牌（omcp_），不配置注册表也不配置旧单租户变量
        if not shared_backend_url:
            raise RuntimeError("MCP_BACKEND_URL is required")
        return []
    else:
        required = (
            "MCP_API_KEY", "MCP_BACKEND_EMAIL", "MCP_BACKEND_PASSWORD",
            "MCP_TENANT_ID", "MCP_USER_ID",
        )
        missing = [key for key in required if not os.environ.get(key)]
        if missing:
            raise RuntimeError("Missing required environment variables: " + ", ".join(missing))
        legacy_key = os.environ["MCP_API_KEY"]
        rows = [{
            "name": f"tenant-{os.environ['MCP_TENANT_ID']}",
            "api_key_sha256": hashlib.sha256(legacy_key.encode("utf-8")).hexdigest(),
            "tenant_id": os.environ["MCP_TENANT_ID"],
            "user_id": os.environ["MCP_USER_ID"],
            "backend_url": shared_backend_url,
            "backend_email": os.environ["MCP_BACKEND_EMAIL"],
            "backend_password": os.environ["MCP_BACKEND_PASSWORD"],
            "store_domain": os.environ.get("MCP_STORE_DOMAIN") or None,
        }]

    configs: list[TenantConfig] = []
    seen_keys: set[str] = set()
    for index, row in enumerate(rows):
        if not isinstance(row, dict):
            raise RuntimeError(f"MCP tenant registry entry {index} must be an object")
        key_hash = str(row.get("api_key_sha256", "")).lower()
        if len(key_hash) != 64 or any(char not in "0123456789abcdef" for char in key_hash):
            raise RuntimeError(f"MCP tenant registry entry {index} has an invalid api_key_sha256")
        if key_hash in seen_keys:
            raise RuntimeError("MCP tenant registry contains duplicate API key hashes")
        seen_keys.add(key_hash)
        try:
            tenant_id = int(row["tenant_id"])
            user_id = int(row["user_id"])
        except (KeyError, TypeError, ValueError) as exc:
            raise RuntimeError(f"MCP tenant registry entry {index} needs integer tenant_id and user_id") from exc
        backend_url = str(row.get("backend_url") or shared_backend_url).rstrip("/")
        values = {
            "backend_url": backend_url,
            "backend_email": row.get("backend_email"),
            "backend_password": row.get("backend_password"),
        }
        missing_values = [name for name, value in values.items() if not value]
        if tenant_id <= 0 or user_id <= 0 or missing_values:
            raise RuntimeError(
                f"MCP tenant registry entry {index} has invalid identity or missing: "
                + ", ".join(missing_values)
            )
        configs.append(TenantConfig(
            name=str(row.get("name") or f"tenant-{tenant_id}"),
            api_key_sha256=key_hash,
            tenant_id=tenant_id,
            user_id=user_id,
            backend_url=backend_url,
            email=str(values["backend_email"]),
            password=str(values["backend_password"]),
            store_domain=str(row["store_domain"]) if row.get("store_domain") else None,
        ))
    return configs


TOKEN_IDLE_SECONDS = int(os.environ.get("MCP_TOKEN_IDLE_SECONDS", 8 * 3600))  # 可用环境变量临时调短做验证； 用户令牌空闲这么久（覆盖一个工作日）就回收它的 app/客户端，下次使用重新核验
MAX_TOKEN_APPS = 500       # 同时缓存的用户令牌上限，超出淘汰最久没用的
SWEEP_SECONDS = 300


class TenantRegistry:
    """Resolve a bearer key to one tenant and keep each backend login isolated."""

    def __init__(self, configs: list[TenantConfig]) -> None:
        self.configs = configs
        self._clients: dict[str, OmniStoreApi] = {}
        self._apps: dict[str, Any] = {}
        self._lifespans: dict[str, tuple[asyncio.Event, asyncio.Task]] = {}
        self._last_used: dict[str, float] = {}  # 只记用户令牌；配置文件里的租户密钥常驻
        self._inflight: dict[str, int] = {}     # 正在处理的请求数，有请求的不回收
        self._lock = asyncio.Lock()

    async def start(self) -> None:
        # Give each key its own FastMCP session manager and server lifespan.
        # Stateful MCP sessions run in SDK-owned tasks, so HTTP request
        # ContextVars do not safely identify the tenant inside tool handlers.
        for config in self.configs:
            await self._add_app(config)

    async def _add_app(self, config: TenantConfig) -> None:
        tenant_mcp = FastMCP(
            "SME OmniStore Product Catalogue",
            instructions=_INSTRUCTIONS,
            host=os.environ.get("MCP_HOST", "127.0.0.1"),
            port=int(os.environ.get("MCP_PORT", "8766")),
            streamable_http_path="/mcp",
            stateless_http=False,
            json_response=True,
            lifespan=self._session_lifespan(config),
        )
        for tool in mcp._tool_manager._tools.values():
            tenant_mcp.add_tool(
                tool.fn,
                name=tool.name,
                title=tool.title,
                description=tool.description,
                annotations=tool.annotations,
                icons=tool.icons,
                meta=tool.meta,
            )
        app = tenant_mcp.streamable_http_app()
        # lifespan 里有 anyio 的 task group / cancel scope，必须在同一个任务里进入和退出。
        # 令牌 app 是在某个 HTTP 请求里懒创建的，请求任务很快结束，所以交给专门的长期任务持有。
        ready: asyncio.Future = asyncio.get_running_loop().create_future()
        stop = asyncio.Event()
        task = asyncio.create_task(self._hold_lifespan(app, ready, stop), name=f"mcp-lifespan-{config.name}")
        await ready
        self._lifespans[config.api_key_sha256] = (stop, task)
        self._apps[config.api_key_sha256] = app

    @staticmethod
    async def _hold_lifespan(app, ready: asyncio.Future, stop: asyncio.Event) -> None:
        try:
            async with app.router.lifespan_context(app):
                ready.set_result(None)
                await stop.wait()
        except BaseException as exc:
            if not ready.done():
                ready.set_exception(exc)
            else:
                raise

    def _session_lifespan(self, config: TenantConfig):
        @asynccontextmanager
        async def lifespan(_server):
            client = await self.client_for(config)
            context_token = _active_api.set(client)
            try:
                yield {}
            finally:
                _active_api.reset(context_token)

        return lifespan

    def resolve(self, api_key: str) -> TenantConfig | None:
        supplied_hash = hashlib.sha256(api_key.encode("utf-8")).hexdigest()
        for config in self.configs:
            if hmac.compare_digest(supplied_hash, config.api_key_sha256):
                return config
        return None

    async def client_for(self, config: TenantConfig) -> OmniStoreApi:
        async with self._lock:
            client = self._clients.get(config.api_key_sha256)
            if client is not None:
                return client
            client = OmniStoreApi(config)
            try:
                await client.start()
            except Exception:
                await client.close()
                raise
            self._clients[config.api_key_sha256] = client
            return client

    def app_for(self, config: TenantConfig):
        return self._apps[config.api_key_sha256]

    async def token_config(self, token: str) -> TenantConfig:
        """用户令牌：首次使用时向后端核验并建独立的 MCP app；之后复用，空闲超时后由 evict_idle 回收。

        返回前已把该令牌记为处理中，调用方处理完必须调用 release。
        """
        key_hash = hashlib.sha256(token.encode("utf-8")).hexdigest()
        config = TenantConfig(
            name=f"token-{token[:12]}", api_key_sha256=key_hash, tenant_id=0, user_id=0,
            backend_url=os.environ.get("MCP_BACKEND_URL", "").rstrip("/"), email="", password="",
            store_domain=None, token=token,
        )
        await self.client_for(config)  # 令牌无效时抛 TokenRejected
        async with self._lock:
            if key_hash not in self._apps:
                await self._add_app(config)
            self._last_used[key_hash] = time.monotonic()
            self._inflight[key_hash] = self._inflight.get(key_hash, 0) + 1
        if len(self._last_used) > MAX_TOKEN_APPS:
            await self.evict_idle(over_limit=True)
        return config

    async def release(self, config: TenantConfig) -> None:
        async with self._lock:
            key = config.api_key_sha256
            self._last_used[key] = time.monotonic()
            if self._inflight.get(key, 0) <= 1:
                self._inflight.pop(key, None)
            else:
                self._inflight[key] -= 1
        # 新增时超限但全都在处理中、没法淘汰的，等它们结束再收；
        # ponytail: 同时在处理的令牌超过上限时缓存会暂时超限——处理中的不能断，这是硬约束
        if len(self._last_used) > MAX_TOKEN_APPS:
            await self.evict_idle(over_limit=True)

    async def evict_idle(self, *, over_limit: bool = False) -> int:
        """回收空闲的用户令牌；over_limit 时再按最久未用淘汰到上限以内。有请求在处理的永不回收。"""
        now = time.monotonic()
        async with self._lock:
            idle = sorted((t, k) for k, t in self._last_used.items() if not self._inflight.get(k))
            victims = [k for t, k in idle if now - t >= TOKEN_IDLE_SECONDS]
            if over_limit:
                extra = len(self._last_used) - len(victims) - MAX_TOKEN_APPS
                victims += [k for _, k in idle if k not in victims][:max(extra, 0)]
            removed = []
            for key in victims:
                self._last_used.pop(key, None)
                self._apps.pop(key, None)
                removed.append((self._lifespans.pop(key, None), self._clients.pop(key, None)))
        for lifespan, client in removed:
            if lifespan:
                lifespan[0].set()
                await asyncio.gather(lifespan[1], return_exceptions=True)
            if client:
                await client.close()
        return len(removed)

    async def sweep_forever(self) -> None:
        while True:
            await asyncio.sleep(SWEEP_SECONDS)
            try:
                await self.evict_idle()
            except Exception:
                logger.exception("MCP token app eviction failed")

    async def close(self) -> None:
        for stop, _ in self._lifespans.values():
            stop.set()
        await asyncio.gather(*(task for _, task in self._lifespans.values()), return_exceptions=True)
        self._lifespans.clear()
        self._last_used.clear()
        self._inflight.clear()
        async with self._lock:
            clients = list(self._clients.values())
            self._clients.clear()
            self._apps.clear()
        await asyncio.gather(*(client.close() for client in clients), return_exceptions=True)


tenant_registry: TenantRegistry | None = None
_active_api: contextvars.ContextVar[OmniStoreApi | None] = contextvars.ContextVar("mcp_tenant_api", default=None)


class TenantApiKeyMiddleware:
    """Authenticate each HTTP request and bind its tenant API client in a task-local context."""

    def __init__(self, app) -> None:
        self.app = app

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return
        registry = tenant_registry
        authorization = dict(scope.get("headers", [])).get(b"authorization", b"").decode("latin-1")
        supplied = authorization[7:].strip() if authorization.lower().startswith("bearer ") else ""
        if registry and supplied.startswith(USER_TOKEN_PREFIX):
            try:
                config = await registry.token_config(supplied)
            except TokenRejected:
                await JSONResponse({"error": "MCP token invalid, revoked or expired"}, status_code=401)(scope, receive, send)
                return
            except Exception:
                logger.exception("MCP backend token verification failed")
                await JSONResponse({"error": "Tenant backend authentication failed"}, status_code=503)(scope, receive, send)
                return
            try:
                await registry.app_for(config)(scope, receive, send)
            finally:
                await registry.release(config)
            return
        config = registry.resolve(supplied) if registry and supplied else None
        if config is None:
            await JSONResponse({"error": "Unauthorized"}, status_code=401)(scope, receive, send)
            return
        try:
            client = await registry.client_for(config)
        except Exception:
            logger.exception("MCP backend authentication failed for tenant_id=%s", config.tenant_id)
            await JSONResponse({"error": "Tenant backend authentication failed"}, status_code=503)(scope, receive, send)
            return
        await registry.app_for(config)(scope, receive, send)


class TenantApiProxy:
    """Preserve the tool API while resolving it from the authenticated request context."""

    @staticmethod
    def _current() -> OmniStoreApi:
        client = _active_api.get()
        if client is None:
            raise RuntimeError("MCP tool request has no authenticated tenant context")
        return client

    def __getattr__(self, name: str):
        return getattr(self._current(), name)

    async def request(self, *args, **kwargs):
        return await self._current().request(*args, **kwargs)


class TokenRejected(Exception):
    """后端拒绝了用户令牌（无效、已撤销或已过期）。"""


class OmniStoreApi:
    """HTTP client bound to one tenant: a registry service user, or a user token forwarded as-is."""

    def __init__(self, config: TenantConfig) -> None:
        self.config = config
        self.base_url = config.backend_url
        self.email = config.email
        self.password = config.password
        self.store_domain = config.store_domain
        self.user_id = config.user_id
        self.tenant_id = config.tenant_id
        self._token: str | None = None
        self._permissions: set[str] = set()
        self._is_superadmin = False
        self._client: httpx.AsyncClient | None = None
        self._permission_checked_at = 0.0

    async def start(self) -> None:
        self._client = httpx.AsyncClient(base_url=self.base_url, timeout=30.0)
        await self._login()

    async def close(self) -> None:
        if self._client:
            await self._client.aclose()
            self._client = None

    async def _login(self) -> None:
        if not self._client:
            raise RuntimeError("MCP backend client is not initialized")
        if self.config.token:
            await self._load_token_permissions()
            return
        response = await self._client.post("/api/auth/login", json={
            "email": self.email,
            "password": self.password,
            "store_domain": self.store_domain,
        })
        if response.is_error:
            raise RuntimeError(f"OmniStore login failed ({response.status_code})")
        data = response.json()
        self._token = data["token"]
        user = data["user"]
        self._is_superadmin = bool(user.get("is_superadmin"))
        if user.get("id") != self.user_id or self._is_superadmin:
            raise RuntimeError("MCP login resolved to the wrong user or a platform superadmin")

        response = await self._client.get(
            "/api/admin/permissions/me",
            headers={"Authorization": f"Bearer {self._token}"},
        )
        if response.is_error:
            raise RuntimeError(f"Could not verify OmniStore permissions ({response.status_code})")
        permission_data = response.json()
        identity = permission_data.get("user", {})
        if identity.get("id") != self.user_id or identity.get("tenant_id") != self.tenant_id:
            raise RuntimeError("MCP backend user does not match the tenant registry binding")
        self._permissions = set(permission_data.get("permissions", []))
        self._permission_checked_at = time.monotonic()

    async def _load_token_permissions(self) -> None:
        # 后端按"用户权限 ∩ 令牌范围"返回，并且是唯一权威；这里只用于提前给出友好报错
        response = await self._client.get(
            "/api/admin/permissions/me", headers={"Authorization": f"Bearer {self.config.token}"},
        )
        if response.status_code in (401, 403):
            raise TokenRejected()
        if response.is_error:
            raise RuntimeError(f"Could not verify OmniStore permissions ({response.status_code})")
        data = response.json()
        self._token = self.config.token
        self.user_id = data.get("user", {}).get("id")
        self.tenant_id = data.get("user", {}).get("tenant_id")
        self._permissions = set(data.get("permissions", []))
        self._permission_checked_at = time.monotonic()

    async def request(
        self,
        method: str,
        path: str,
        *,
        permission: str,
        params: dict[str, Any] | None = None,
        json: Any = None,
        files: dict[str, Any] | None = None,
    ) -> Any:
        if not self._client:
            raise RuntimeError("MCP backend client is not initialized")
        for attempt in range(2):
            if not self._token:
                await self._login()
            elif time.monotonic() - self._permission_checked_at > 60:
                await self._login()
            if permission not in self._permissions:
                raise PermissionError(f"MCP service user lacks permission: {permission}")
            response = await self._client.request(
                method,
                "/api/" + path.lstrip("/"),
                params=params,
                json=json,
                files=files,
                headers={"Authorization": f"Bearer {self._token}"},
            )
            if response.status_code == 401 and self.config.token:
                raise PermissionError("MCP token is invalid, revoked or expired")
            if response.status_code == 401 and attempt == 0:
                self._token = None
                await self._login()
                continue
            if response.is_error:
                try:
                    detail = response.json().get("detail", response.text)
                except ValueError:
                    detail = response.text
                raise ValueError(f"OmniStore API {response.status_code}: {detail}")
            if response.status_code == 204 or not response.content:
                return {"ok": True}
            return response.json()
        raise RuntimeError("OmniStore authentication retry failed")


api = TenantApiProxy()


@asynccontextmanager
async def _application_lifespan(_app):
    global tenant_registry
    tenant_registry = TenantRegistry(_tenant_configs_from_environment())
    await tenant_registry.start()
    sweeper = asyncio.create_task(tenant_registry.sweep_forever(), name="mcp-token-sweeper")
    try:
        yield
    finally:
        sweeper.cancel()
        await asyncio.gather(sweeper, return_exceptions=True)
        await tenant_registry.close()
        tenant_registry = None


mcp = FastMCP(
    "SME OmniStore Product Catalogue",
    instructions=_INSTRUCTIONS,
    host=os.environ.get("MCP_HOST", "127.0.0.1"),
    port=int(os.environ.get("MCP_PORT", "8766")),
    streamable_http_path="/mcp",
    stateless_http=False,
    json_response=True,
)
_root_app = Starlette(lifespan=_application_lifespan)
mcp_app = TenantApiKeyMiddleware(_root_app)


@mcp.tool()
async def search_products(
    keyword: str = "", category_id: int | None = None, brand_id: int | None = None,
    status: str | None = None, page: int = 1, page_size: int = 20,
) -> dict:
    """Search products by name, SKU, or barcode in the configured tenant."""
    if page < 1 or not 1 <= page_size <= 100:
        raise ValueError("page must be >= 1 and page_size must be between 1 and 100")
    params = {"page": page, "page_size": page_size}
    if keyword.strip(): params["keyword"] = keyword.strip()
    if category_id is not None: params["category_id"] = category_id
    if brand_id is not None: params["brand_id"] = brand_id
    if status: params["status"] = status
    return await api.request("GET", "products", permission="products.view", params=params)


@mcp.tool()
async def get_product(product_id: int) -> dict:
    """Read product details, variants, categories, tier prices and media."""
    result = await api.request("GET", f"products/{product_id}", permission="products.view")
    return _redact_cost(result)


def _redact_cost(result: dict) -> dict:
    if "products.cost_price.view" not in api._permissions:
        for key in ("cost_price", "inventory_current_unit_cost", "inventory_last_purchase_unit_cost"):
            result.pop(key, None)
        result["inventory_cost_managed"] = False
    return result


@mcp.tool()
async def create_product(product: dict) -> dict:
    """Create a product with fields supported by the Admin ProductCreate API, including variants, barcodes, categories and tier prices."""
    payload = dict(product)
    payload["stock_qty"] = 0
    for variant in payload.get("variants", []):
        variant["stock_qty"] = 0
        variant["reserved_qty"] = 0
    if payload.get("cost_price") is not None and "products.cost_price.view" not in api._permissions:
        raise PermissionError("MCP service user lacks permission: products.cost_price.view")
    return _redact_cost(await api.request("POST", "products", permission="products.create", json=payload))


@mcp.tool()
async def update_product(product_id: int, changes: dict) -> dict:
    """Update product fields. Inventory values are ignored and current variant quantities are preserved."""
    payload = dict(changes)
    payload.pop("stock_qty", None)
    payload.pop("reserved_qty", None)
    payload.pop("stock_status_id", None)
    if "cost_price" in payload and "products.cost_price.view" not in api._permissions:
        raise PermissionError("MCP service user lacks permission: products.cost_price.view")
    if payload.get("variants") is not None:
        current = await api.request("GET", f"products/{product_id}", permission="products.view")
        stock = {v["id"]: (v.get("stock_qty", 0), v.get("reserved_qty", 0)) for v in current.get("variants", [])}
        for variant in payload["variants"]:
            old = stock.get(variant.get("id"), (0, 0))
            variant["stock_qty"], variant["reserved_qty"] = old
    return _redact_cost(await api.request("PUT", f"products/{product_id}", permission="products.update", json=payload))


@mcp.tool()
async def set_product_stock(product_id: int, quantity: float) -> dict:
    """Set stock for a product without variants when the tenant inventory ledger is not enabled; fails closed otherwise."""
    if not math.isfinite(quantity) or quantity < 0:
        raise ValueError("quantity must be a finite number greater than or equal to zero")
    settings = await api.request(
        "GET", "admin/inventory/settings", permission="inventory.view",
    )
    if settings is not None:
        raise ValueError("Inventory ledger is enabled; stock must be changed through an inventory adjustment document")
    product = await api.request("GET", f"products/{product_id}", permission="products.view")
    if product.get("variants"):
        raise ValueError("This tool only sets aggregate stock for products without variants")
    updated = await api.request(
        "PUT", f"products/{product_id}", permission="products.update",
        json={"stock_qty": quantity},
    )
    actual = updated.get("stock_qty")
    if actual is None or not math.isclose(float(actual), quantity, rel_tol=0, abs_tol=1e-9):
        raise RuntimeError("Stock update did not persist the requested quantity")
    return {
        "id": updated["id"],
        "tenant_id": api.tenant_id,
        "stock_qty": actual,
        "reserved_qty": updated.get("reserved_qty", 0),
        "stock_status_id": updated.get("stock_status_id"),
    }


@mcp.tool()
async def list_inventory_warehouses() -> list[dict]:
    """List warehouses available to the authenticated tenant before preparing a stock adjustment."""
    return await api.request("GET", "admin/inventory/warehouses", permission="inventory.view")


@mcp.tool()
async def list_inventory_balances(
    product_id: int | None = None, warehouse_id: int | None = None, limit: int = 100,
) -> list[dict]:
    """Read non-zero inventory-ledger balances by product variant and warehouse."""
    if not 1 <= limit <= 500:
        raise ValueError("limit must be between 1 and 500")
    params = {"limit": limit}
    if product_id is not None:
        params["product_id"] = product_id
    if warehouse_id is not None:
        params["warehouse_id"] = warehouse_id
    return await api.request("GET", "admin/inventory/balances", permission="inventory.view", params=params)


@mcp.tool()
async def list_inventory_adjustments(state: str | None = None) -> list[dict]:
    """List inventory adjustment documents, optionally filtered by draft/done state."""
    params = {"state": state} if state else None
    return await api.request("GET", "admin/inventory/adjustments", permission="inventory.view", params=params)


@mcp.tool()
async def get_inventory_adjustment(operation_id: int) -> dict:
    """Read an adjustment document and its variant, warehouse, quantity, and posting details."""
    return await api.request(
        "GET", f"admin/inventory/adjustments/{operation_id}", permission="inventory.view",
    )


def _inventory_adjustment_payload(
    reason: str, lines: list[dict], reference: str | None, idempotency_key: str | None,
) -> dict:
    if not reason.strip():
        raise ValueError("reason is required")
    if not lines:
        raise ValueError("at least one adjustment line is required")
    normalized = []
    for line in lines:
        item = dict(line)
        if not item.get("product_id") or not item.get("warehouse_id"):
            raise ValueError("each line requires product_id and warehouse_id")
        if "qty_delta" not in item or not math.isfinite(float(item["qty_delta"])) or float(item["qty_delta"]) == 0:
            raise ValueError("each line requires a non-zero finite qty_delta")
        item["variant_id"] = item.get("variant_id") or None
        normalized.append(item)
    return {
        "reason": reason.strip(),
        "reference": reference,
        "lines": normalized,
        "idempotency_key": idempotency_key,
    }


@mcp.tool()
async def create_inventory_adjustment(
    reason: str, lines: list[dict], reference: str | None = None,
    idempotency_key: str | None = None,
) -> dict:
    """Create a draft stock adjustment for specific variants and warehouses; drafts do not change inventory."""
    payload = _inventory_adjustment_payload(reason, lines, reference, idempotency_key)
    return await api.request(
        "POST", "admin/inventory/adjustments", permission="inventory.adjust", json=payload,
    )


@mcp.tool()
async def update_inventory_adjustment(
    operation_id: int, reason: str, lines: list[dict], reference: str | None = None,
    idempotency_key: str | None = None,
) -> dict:
    """Replace the contents of a draft adjustment document; posted documents cannot be edited."""
    payload = _inventory_adjustment_payload(reason, lines, reference, idempotency_key)
    return await api.request(
        "PUT", f"admin/inventory/adjustments/{operation_id}",
        permission="inventory.adjust", json=payload,
    )


@mcp.tool()
async def post_inventory_adjustment(operation_id: int) -> dict:
    """Post a draft adjustment. This writes audited inventory movements and changes variant sellable stock."""
    return await api.request(
        "POST", f"admin/inventory/adjustments/{operation_id}/post", permission="inventory.adjust",
    )


@mcp.tool()
async def cancel_inventory_adjustment(operation_id: int) -> dict:
    """Cancel a draft inventory adjustment; posted documents cannot be cancelled through this operation."""
    return await api.request(
        "POST", f"admin/inventory/adjustments/{operation_id}/cancel", permission="inventory.adjust",
    )


@mcp.tool()
async def list_categories(keyword: str = "", parent_id: int | None = None) -> list[dict]:
    """List categories in the configured tenant."""
    params = {}
    if keyword: params["keyword"] = keyword
    if parent_id is not None: params["parent_id"] = parent_id
    return await api.request("GET", "categories", permission="categories.view", params=params)


@mcp.tool()
async def create_category(category: dict) -> dict:
    """Create a bilingual, hierarchical category with navigation and SEO fields."""
    return await api.request("POST", "categories", permission="categories.create", json=category)


@mcp.tool()
async def update_category(category_id: int, changes: dict) -> dict:
    """Update category fields. Category deletion is not exposed."""
    return await api.request("PUT", f"categories/{category_id}", permission="categories.update", json=changes)


@mcp.tool()
async def list_brands(keyword: str = "", page: int = 1, page_size: int = 100) -> dict:
    """List brands in the configured tenant."""
    return await api.request("GET", "brands", permission="brands.view", params={
        "keyword": keyword or None, "page": page, "page_size": min(max(page_size, 1), 100),
    })


@mcp.tool()
async def create_brand(brand: dict) -> dict:
    """Create a brand with bilingual, logo, website, country and SEO fields."""
    return await api.request("POST", "brands", permission="brands.create", json=brand)


@mcp.tool()
async def update_brand(brand_id: int, changes: dict) -> dict:
    """Update brand fields. Brand deletion is not exposed."""
    return await api.request("PUT", f"brands/{brand_id}", permission="brands.update", json=changes)


@mcp.tool()
async def list_member_levels() -> dict:
    """List member levels available for product tier prices."""
    return await api.request("GET", "member-levels", permission="member_levels.view", params={"page": 1, "page_size": 100})


@mcp.tool()
async def list_stock_statuses() -> list[dict]:
    """List configured stock-status choices; this does not change inventory."""
    return await api.request("GET", "admin/stock-statuses", permission="products.view")


@mcp.tool()
async def get_product_price_rules(product_id: int) -> dict:
    """Read a product's current price rules and optimistic-lock version."""
    return await api.request("GET", f"products/{product_id}/price-rules", permission="products.view")


@mcp.tool()
async def replace_product_price_rules(product_id: int, ruleset: dict) -> dict:
    """Atomically replace product pricing rules; this affects Store/POS prices and catalogue revision."""
    return await api.request("PUT", f"products/{product_id}/price-rules", permission="products.update", json=ruleset)


@mcp.tool()
async def list_price_rules(
    keyword: str = "", price_group: str | None = None, status: str | None = None,
    page: int = 1, page_size: int = 50,
) -> dict:
    """List tenant-wide product price rules, status and expiry summaries."""
    params = {"page": page, "page_size": min(max(page_size, 1), 200)}
    if keyword: params["keyword"] = keyword
    if price_group is not None: params["price_group"] = price_group
    if status: params["status"] = status
    return await api.request("GET", "price-rules", permission="products.view", params=params)


@mcp.tool()
async def assign_price_group(product_ids: list[int], price_group: str | None) -> dict:
    """Assign or clear a price group for tenant-owned products."""
    return await api.request("PUT", "price-rules/groups", permission="products.update", json={
        "product_ids": product_ids, "price_group": price_group,
    })


@mcp.tool()
async def list_product_images(product_id: int) -> list[dict]:
    """List product image metadata by URL."""
    return await api.request("GET", f"products/{product_id}/images", permission="products.view")


@mcp.tool()
async def upload_product_image(filename: str, content_type: str, image_base64: str) -> dict:
    """Upload a base64-encoded JPEG, PNG, WebP or GIF (up to 5 MB) through the tenant's normal upload API and return its URL."""
    allowed_types = {"image/jpeg", "image/png", "image/webp", "image/gif", "image/jpg"}
    if content_type.lower() not in allowed_types:
        raise ValueError("content_type must be JPEG, PNG, WebP or GIF")
    try:
        content = base64.b64decode(image_base64, validate=True)
    except (binascii.Error, ValueError) as exc:
        raise ValueError("image_base64 must be valid base64") from exc
    if not content or len(content) > 5 * 1024 * 1024:
        raise ValueError("image must be non-empty and no larger than 5 MB")
    safe_filename = Path(filename).name or "product-image.jpg"
    return await api.request(
        "POST", "upload", permission="products.images.upload",
        files={"file": (safe_filename, content, content_type.lower())},
    )


@mcp.tool()
async def add_product_image(product_id: int, image: dict) -> dict:
    """Attach an existing image URL and metadata to a product."""
    return await api.request("POST", f"products/{product_id}/images", permission="products.images.upload", json=image)


@mcp.tool()
async def update_product_image(product_id: int, image_id: int, changes: dict) -> dict:
    """Update image alt text, order or primary-image status."""
    return await api.request("PUT", f"products/{product_id}/images/{image_id}", permission="products.images.upload", json=changes)


@mcp.tool()
async def delete_product_image(product_id: int, image_id: int) -> dict:
    """Delete a product image metadata row."""
    return await api.request("DELETE", f"products/{product_id}/images/{image_id}", permission="products.images.upload")


@mcp.tool()
async def list_product_attachments(product_id: int) -> list[dict]:
    """List product manuals, specifications, and other attachment records."""
    return await api.request("GET", f"admin/products/{product_id}/attachments", permission="products.view")


@mcp.tool()
async def list_attachment_types() -> list[dict]:
    """List configured product attachment types."""
    return await api.request("GET", "admin/product-attachment-types", permission="products.view")


@mcp.tool()
async def create_product_attachment(product_id: int, attachment: dict) -> dict:
    """Attach an existing document URL to a product."""
    return await api.request("POST", f"admin/products/{product_id}/attachments", permission="products.update", json=attachment)


@mcp.tool()
async def update_product_attachment(attachment_id: int, attachment: dict) -> dict:
    """Update an attachment URL, type, title, or visibility."""
    return await api.request("PUT", f"admin/product-attachments/{attachment_id}", permission="products.update", json=attachment)


@mcp.tool()
async def list_product_media_roles(product_id: int) -> list[dict]:
    """List product gallery items grouped by media role."""
    return await api.request("GET", f"admin/products/{product_id}/media-role-items", permission="products.view")


@mcp.tool()
async def list_media_role_options() -> list[dict]:
    """List configured product media roles."""
    return await api.request("GET", "admin/product-media-roles", permission="products.view")


@mcp.tool()
async def create_product_media_role(product_id: int, media: dict) -> dict:
    """Add an existing image URL under a product media role."""
    return await api.request("POST", f"admin/products/{product_id}/media-role-items", permission="products.update", json=media)


@mcp.tool()
async def update_product_media_role(item_id: int, media: dict) -> dict:
    """Update a product gallery item's role, URL, alt text, or visibility."""
    return await api.request("PUT", f"admin/product-media-role-items/{item_id}", permission="products.update", json=media)


@mcp.tool()
async def list_product_selling_units(product_id: int) -> list[dict]:
    """List selling units and effective prices for a product."""
    return await api.request("GET", f"admin/unit-split/products/{product_id}/units", permission="products.view")


@mcp.tool()
async def list_selling_unit_options() -> list[dict]:
    """List configured unit names for product selling-unit setup."""
    return await api.request("GET", "admin/unit-split/dict", permission="products.view")


@mcp.tool()
async def create_product_selling_unit(product_id: int, unit: dict) -> dict:
    """Add a product sales unit with base-quantity conversion and optional price."""
    return await api.request("POST", f"admin/unit-split/products/{product_id}/units", permission="products.update", json=unit)


@mcp.tool()
async def update_product_selling_unit(unit_id: int, unit: dict) -> dict:
    """Update a product sales-unit conversion or override price."""
    return await api.request("PUT", f"admin/unit-split/units/{unit_id}", permission="products.update", json=unit)


# Statistics, inventory, and POS-admin gateway. Each group is one MCP tool whose
# endpoint argument must be a key of its whitelist: (method, path, permission, needs_cost).
# Writes only create or edit drafts and settings; posting, approval, receiving,
# cancellation, and repack execution stay in the admin UI on purpose.
_COST_PERMISSION = "products.cost_price.view"
_INV = "admin/inventory/"
_GATEWAY_TOOLS: dict[str, tuple[str, dict[str, tuple[str, str, str, bool]]]] = {
    "dashboard_stats": (
        "Quick dashboard figures; only paid/shipped/completed orders count. params: range = 7d | 30d | 90d | custom "
        "(custom needs date_start and date_end, YYYY-MM-DD; category_sales_detail also accepts today); "
        "top_products / top_customers take limit; product_sales takes keyword, "
        "sort_by = revenue | quantity | orders_count | avg_unit_price, page, page_size (<=100). "
        "For other periods or filters use advanced_stats.", {
        name: ("GET", f"dashboard/{name.replace('_', '-')}", "dashboard.view", False)
        for name in (
            "stats", "trend", "order_status", "top_products", "top_customers", "customer_growth",
            "category_sales", "category_sales_detail", "product_sales", "inventory_alerts",
            "coupon_stats", "review_stats",
        )
    }),
    "advanced_stats": (
        "Multi-dimension sales reports and order/line drill-down. Key params: dimension = summary | product | "
        "category | brand | member_level | payment_method | pos_payment_method | shipping_method | country | city | "
        "day_of_week | hour | coupon | points | wallet | pos_store | pos_lane | pos_operator | unpaid ...; "
        "granularity = day | week | month | quarter | year (summary only); range = today | yesterday | week | month | "
        "quarter | year | current_* | last_* | all_time | custom (with date_start/date_end); source = all | pos | "
        "non_pos | hungrypanda; statuses (default paid statuses); sort = dim_key or a metric such as total, "
        "orders, quantity, revenue; order = asc | desc; page_size 5-1000. Filters: pos_store_ids, pos_lane_ids, "
        "pos_operator_ids, product_ids, category_ids, brand_ids, product_keyword, order_no_from/order_no_to, "
        "total_min/total_max. List filters go in params as JSON arrays. details endpoint: details = order | item, "
        "detail_sort (created_at, order_no, grand_total, quantity...), detail_order; it returns customer PII. "
        "options returns valid ids for the filters. See usage_guide for recipes.", {
        "report": ("GET", "admin/adv-stats/report", "adv_stats.view", False),
        "options": ("GET", "admin/adv-stats/report/options", "adv_stats.view", False),
        "hungrypanda_shops": ("GET", "admin/adv-stats/report/hungrypanda-shops", "adv_stats.view", False),
        "presets": ("GET", "admin/adv-stats/presets", "adv_stats.view", False),
        "details": ("GET", "admin/adv-stats/report/details", "adv_stats.detail", False),
    }),
    "inventory_query": ("Read inventory settings, master data, documents (purchase orders, receipts, stocktakes, transfers, fulfillment), batches and traceability.", {
        "settings": ("GET", _INV + "settings", "inventory.view", False),
        "tax_rates": ("GET", _INV + "tax-rates", "inventory.view", False),
        "policy": ("GET", _INV + "policy", "inventory.view", False),
        "product_profile": ("GET", _INV + "products/{product_id}/profile", "inventory.view", False),
        "locations": ("GET", _INV + "locations", "inventory.view", False),
        "putaway_rules": ("GET", _INV + "putaway-rules", "inventory.view", False),
        "transactions": ("GET", _INV + "transactions", "inventory.view", False),
        "suppliers": ("GET", _INV + "suppliers", "inventory.view", False),
        "supplier_products": ("GET", _INV + "supplier-products", "inventory.view", True),
        "receipt_party_mappings": ("GET", _INV + "receipt-party-mappings", "inventory.view", False),
        "receipt_party_names": ("GET", _INV + "receipt-party-names", "inventory.view", False),
        "purchase_orders": ("GET", _INV + "purchase-orders", "inventory.view", True),
        "purchase_order": ("GET", _INV + "purchase-orders/{po_id}", "inventory.view", True),
        "receipts": ("GET", _INV + "receipts", "inventory.view", True),
        "receipt": ("GET", _INV + "receipts/{operation_id}", "inventory.view", True),
        "direct_receipt_parse_status": ("GET", _INV + "direct-receipts/ai-parse/{task_id}", "inventory.purchase", True),
        "operations": ("GET", _INV + "operations", "inventory.view", False),
        "transfers": ("GET", _INV + "transfers", "inventory.view", False),
        "transfer": ("GET", _INV + "transfers/{operation_id}", "inventory.view", False),
        "stocktakes": ("GET", _INV + "stocktakes", "inventory.view", False),
        "stocktake": ("GET", _INV + "stocktakes/{operation_id}", "inventory.view", False),
        "fulfillment_orders": ("GET", _INV + "fulfillment/orders", "inventory.view", False),
        "fulfillment_order": ("GET", _INV + "fulfillment/orders/{order_id}", "inventory.view", False),
        "lockable_batches": ("GET", _INV + "batches/lockable", "inventory.view", False),
        "batches": ("GET", _INV + "batches", "inventory.view", False),
        "trace_lot": ("GET", _INV + "trace/lots/{batch_id}", "inventory.view", False),
        "trace_serial": ("GET", _INV + "trace/serials/{serial_no}", "inventory.view", False),
        "replenishment_rules": ("GET", _INV + "replenishment/rules", "inventory.view", False),
        "replenishment_suggestions": ("GET", _INV + "replenishment/suggestions", "inventory.view", False),
        "revaluations": ("GET", _INV + "revaluations", "inventory.view", True),
        "warehouse_mapping_overview": ("GET", _INV + "warehouse-mapping/overview", "inventory.view", False),
        "warehouse_mapping_options": ("GET", _INV + "warehouse-mapping/options", "inventory.view", False),
        "warehouse_mapping_stores": ("GET", _INV + "warehouse-mapping/stores", "inventory.view", False),
        "warehouse_mapping_channels": ("GET", _INV + "warehouse-mapping/channels", "inventory.view", False),
        "order_warehouse_overrides": ("GET", _INV + "orders/{order_id}/warehouse-override", "inventory.view", False),
    }),
    "inventory_reports": ("Read inventory reports and the ledger reconciliation check.", {
        "stock_value": ("GET", _INV + "reports/stock-value", "inventory.view", True),
        "low_stock": ("GET", _INV + "reports/low-stock", "inventory.view", False),
        "expiring": ("GET", _INV + "reports/expiring", "inventory.view", False),
        "unallocated": ("GET", _INV + "reports/unallocated", "inventory.view", False),
        "forecast": ("GET", _INV + "reports/forecast", "inventory.view", False),
        "aging": ("GET", _INV + "reports/aging", "inventory.view", False),
        "anomalies": ("GET", _INV + "reports/anomalies", "inventory.view", False),
        "fulfillment": ("GET", _INV + "reports/fulfillment", "inventory.view", False),
        "suppliers": ("GET", _INV + "reports/suppliers", "inventory.view", False),
        "sales_gross_profit": ("GET", _INV + "reports/sales-gross-profit", "inventory.view", True),
        "order_profit": ("GET", _INV + "reports/order-profit", "inventory.view", True),
        "reconcile": ("GET", _INV + "reconcile", "inventory.view", False),
    }),
    "pos_admin_query": ("Read POS back-office data: payment reconciliation, sync conflicts, wallet top-ups, staff, rules and returns.", {
        "reconciliation_cases": ("GET", "admin/pos/reconciliation", "pos.reconciliation.view", False),
        "sync_conflicts": ("GET", "admin/pos/reconciliation/sync-conflicts", "pos.reconciliation.view", False),
        "reconciliation_lanes": ("GET", "admin/pos/reconciliation/lanes", "pos.reconciliation.view", False),
        "wallet_topups": ("GET", "admin/pos/wallet/topups", "adv_stats.view", False),
        "wallet_reconcile": ("GET", "admin/pos/wallet/reconcile", "adv_stats.view", False),
        "wallet_rules": ("GET", "admin/pos/wallet/rules", "adv_stats.view", False),
        "product_channel": ("GET", "admin/pos/product-channels/{product_id}", "products.view", False),
        "staff": ("GET", "pos/operations/admin/staff", "pos.staff.manage", False),
        "assignable_users": ("GET", "pos/operations/admin/assignable-users", "pos.staff.manage", False),
        # ponytail: backend accepts any of staff/rules/audit; the gateway checks one.
        "stores": ("GET", "pos/operations/admin/stores", "pos.audit.view", False),
        "rules": ("GET", "pos/operations/admin/rules", "pos.rules.manage", False),
        "quick_buttons": ("GET", "pos/operations/admin/quick-buttons", "pos.rules.manage", False),
        "barcode_prefixes": ("GET", "pos/operations/admin/barcode-prefixes", "pos.rules.manage", False),
        "product_ages": ("GET", "pos/operations/admin/product-ages", "pos.rules.manage", False),
        "returns": ("GET", "pos/operations/admin/returns", "pos.audit.view", False),
    }),
    "customer_return_query": ("Read a customer's recent purchases of one product (params product_id, limit) and unsellable-return summaries.", {
        "product_purchases": ("GET", "customers/{customer_id}/product-purchases", "customers.view", False),
        "return_records_summary": ("GET", "admin/return-collections/records/summary", "return_collections.view", False),
    }),
    "stock_alerts_and_statuses": ("Read and maintain low-stock alert thresholds, and create or edit stock-status choices (no deletion).", {
        "list_alerts": ("GET", "admin/inventory-alerts", "products.view", False),
        "set_alert": ("POST", "admin/inventory-alerts", "products.update", False),
        "update_alert": ("PUT", "admin/inventory-alerts/{alert_id}", "products.update", False),
        "delete_alert": ("DELETE", "admin/inventory-alerts/{alert_id}", "products.update", False),
        "create_stock_status": ("POST", "admin/stock-statuses", "products.update", False),
        "update_stock_status": ("PUT", "admin/stock-statuses/{status_id}", "products.update", False),
    }),
    "repack": ("Read and maintain big-pack to small-pack repack rules and preview a repack. Executing a repack is not exposed.", {
        "rules": ("GET", "admin/repack/rules", "repack.view", False),
        "create_rule": ("POST", "admin/repack/rules", "repack.manage", False),
        "update_rule": ("PUT", "admin/repack/rules/{rule_id}", "repack.manage", False),
        "preview": ("GET", "admin/repack/preview", "repack.view", False),
        "logs": ("GET", "admin/repack/logs", "repack.view", False),
    }),
    "inventory_drafts": (
        "Create or edit DRAFT inventory documents; drafts do not change stock. Submitting a purchase order only "
        "requests approval. Approval, receiving, validation, posting, shipping and cancellation are done by staff "
        "in the admin UI. Put an idempotency_key in the body where supported and reuse it when retrying.", {
            "create_purchase_order": ("POST", _INV + "purchase-orders", "inventory.purchase", True),
            "update_purchase_order": ("PUT", _INV + "purchase-orders/{po_id}", "inventory.purchase", True),
            "submit_purchase_order": ("POST", _INV + "purchase-orders/{po_id}/submit", "inventory.purchase", False),
            "create_receipt": ("POST", _INV + "receipts", "inventory.purchase", False),
            "update_receipt": ("PUT", _INV + "receipts/{operation_id}", "inventory.purchase", False),
            "create_direct_receipt": ("POST", _INV + "direct-receipts", "inventory.purchase", True),
            "update_direct_receipt": ("PUT", _INV + "direct-receipts/{operation_id}", "inventory.purchase", True),
            "create_stocktake": ("POST", _INV + "stocktakes", "inventory.operate", False),
            "update_stocktake": ("PUT", _INV + "stocktakes/{operation_id}", "inventory.operate", False),
            "create_transfer": ("POST", _INV + "transfers", "inventory.operate", False),
            "update_transfer": ("PUT", _INV + "transfers/{operation_id}", "inventory.operate", False),
            "create_vendor_return": ("POST", _INV + "vendor-returns", "inventory.purchase", False),
        },
    ),
    "inventory_replenishment": ("Save reorder rules, generate replenishment suggestions, and convert suggestions into DRAFT purchase orders.", {
        "save_rule": ("POST", _INV + "replenishment/rules", "inventory.operate", False),
        "generate": ("POST", _INV + "replenishment/generate", "inventory.operate", False),
        "convert": ("POST", _INV + "replenishment/convert", "inventory.operate", False),
    }),
    "inventory_master_data": ("Create or edit suppliers, supplier catalogue items, locations, putaway rules and receipt-party mappings, and create warehouses. Warehouse edits, warehouse mapping and product inventory profiles are not exposed.", {
        "create_supplier": ("POST", _INV + "suppliers", "inventory.purchase", False),
        "update_supplier": ("PUT", _INV + "suppliers/{supplier_id}", "inventory.purchase", False),
        "create_supplier_product": ("POST", _INV + "supplier-products", "inventory.purchase", True),
        "update_supplier_product": ("PUT", _INV + "supplier-products/{catalog_id}", "inventory.purchase", True),
        "save_receipt_party_mapping": ("PUT", _INV + "receipt-party-mappings", "inventory.purchase", False),
        "create_location": ("POST", _INV + "locations", "inventory.manage", False),
        "update_location": ("PUT", _INV + "locations/{location_id}", "inventory.manage", False),
        "create_putaway_rule": ("POST", _INV + "putaway-rules", "inventory.manage", False),
        "update_putaway_rule": ("PUT", _INV + "putaway-rules/{rule_id}", "inventory.manage", False),
        "create_warehouse": ("POST", _INV + "warehouses", "inventory.manage", False),
    }),
}


def _gateway_path(template: str, path_params: dict) -> str:
    missing = [name for name in re.findall(r"\{(\w+)\}", template) if name not in path_params]
    if missing:
        raise ValueError("path_params is missing: " + ", ".join(missing))
    return re.sub(r"\{(\w+)\}", lambda match: quote(str(path_params[match.group(1)]), safe=""), template)


def _strip_cost(value: Any) -> Any:
    if isinstance(value, dict):
        return {key: _strip_cost(item) for key, item in value.items() if "cost" not in key.lower()}
    if isinstance(value, list):
        return [_strip_cost(item) for item in value]
    return value


async def _call_gateway(
    group: str, endpoint: str, path_params: dict | None, params: dict | None, body: dict | None,
) -> Any:
    endpoints = _GATEWAY_TOOLS[group][1]
    if endpoint not in endpoints:
        raise ValueError(f"Unknown endpoint for {group}; choose one of: " + ", ".join(endpoints))
    method, template, permission, needs_cost = endpoints[endpoint]
    if needs_cost and _COST_PERMISSION not in api._permissions:
        raise PermissionError(f"MCP service user lacks permission: {_COST_PERMISSION}")
    if method == "GET" and body is not None:
        raise ValueError("body is only accepted by write endpoints")
    if group == "advanced_stats" and params:
        # 后端 ReportQuery 用 Depends() 收参，list 字段只认 JSON body，放查询串会被静默忽略
        lists = {key: value for key, value in params.items() if isinstance(value, list)}
        params = {key: value for key, value in params.items() if key not in lists}
        body = lists or None
    result = await api.request(
        method, _gateway_path(template, path_params or {}), permission=permission,
        params=params, json=body,
    )
    return result if _COST_PERMISSION in api._permissions else _strip_cost(result)


def _load_usage_guides(directory: Path) -> dict[str, str]:
    """Load stable topics from the deployment Markdown files; fail closed on broken docs."""
    guides: dict[str, str] = {}
    for filename in ("AI_USAGE_GUIDE.md", "API_REFERENCE.md", "API_COVERAGE.md"):
        try:
            content = (directory / filename).read_text(encoding="utf-8")
        except (OSError, UnicodeError) as exc:
            raise RuntimeError(f"Could not read MCP guide file: {filename}") from exc
        topic = None
        body: list[str] = []
        fence = None
        for line in content.splitlines(keepends=True):
            fence_match = re.match(r"^ {0,3}(`{3,}|~{3,})", line)
            if fence_match:
                marker = fence_match[1]
                if fence is None:
                    fence = marker
                elif marker[0] == fence[0] and len(marker) >= len(fence) and not line[fence_match.end():].strip():
                    fence = None
                if topic:
                    body.append(line)
                continue
            if fence is not None:
                if topic:
                    body.append(line)
                continue
            start = re.fullmatch(r"<!-- mcp-topic: ([A-Za-z0-9_]+) -->", line.strip())
            if start:
                if topic or start[1] in guides or start[1] == "index":
                    raise RuntimeError(f"Duplicate or nested MCP guide topic: {start[1]} in {filename}")
                topic, body = start[1], []
            elif line.strip() == "<!-- /mcp-topic -->":
                if topic is None:
                    raise RuntimeError(f"Unmatched MCP guide end marker in {filename}")
                value = "".join(body).strip()
                if not value:
                    raise RuntimeError(f"Empty MCP guide topic: {topic}")
                guides[topic] = value
                topic, body = None, []
            elif "<!-- mcp-topic:" in line:
                raise RuntimeError(f"Malformed MCP guide topic marker in {filename}")
            elif topic:
                body.append(line)
        if topic:
            raise RuntimeError(f"Unclosed MCP guide topic: {topic} in {filename}")
    required = {"rules", "authentication", "parameters", "statistics", "recent_orders_items", "top_products",
                "sales_by_period", "pos_compare", "products", "pricing", "media", "units", "inventory_query",
                "inventory_reports", "inventory_master_data", "inventory_drafts", "stock_alerts", "low_stock_to_po",
                "inventory_adjustments", "receipt_ai", "returns", "errors", "api_coverage", "reference_standalone",
                "reference_products", "reference_pricing", "reference_images", "reference_units", "reference_catalog",
                "reference_inventory_adjustments", "reference_attachments_media", "reference_usage_guide", "reference_receipt_ai"}
    required.update("reference_" + name for name in _GATEWAY_TOOLS)
    if missing := required - guides.keys():
        raise RuntimeError("Missing MCP guide topics: " + ", ".join(sorted(missing)))
    models = {name.removeprefix("schema_"): name for name in guides if name.startswith("schema_")}
    for name, value in list(guides.items()):
        if name.startswith(("reference_", "schema_")):
            references = sorted(target for model, target in models.items()
                                if target != name and re.search(r"(?<![A-Za-z0-9_])" + re.escape(model)
                                                               + r"(?![A-Za-z0-9_])", value))
            if references:
                guides[name] += "\n\n模型详情按需调用 usage_guide(topic=对应标识)：" + ", ".join(references)
    index = "# OmniStore MCP 说明索引\n\n先读 rules、authentication、parameters，再选择业务主题。"
    index += "模型按需另取；reference_standalone 是兼容旧调用的独立工具短索引。\n\n"
    for name, value in guides.items():
        title = re.search(r"^#{1,6} (.+)$", value, re.MULTILINE)
        index += f"- `{name}`：{title[1] if title else name}\n"
    guides = {"index": index, **guides}
    oversized = [name for name, value in guides.items() if len(value) > 24000]
    if oversized:
        raise RuntimeError("MCP guide topics exceed 24000 characters: " + ", ".join(oversized))
    return guides


_USAGE_GUIDES: dict[str, str] = _load_usage_guides(Path(__file__).resolve().parent)


@mcp.tool()
async def usage_guide(topic: Literal[tuple(_USAGE_GUIDES)] = "index") -> str:
    """Step-by-step recipes for common questions (recent order items, best sellers, sales trend, POS comparison,
    low stock to draft purchase order, error meanings). Call with topic='index' first if unsure."""
    return _USAGE_GUIDES[topic]


def _register_gateway_tool(name: str) -> None:
    description, endpoints = _GATEWAY_TOOLS[name]

    async def gateway_tool(
        endpoint: str, path_params: dict | None = None, params: dict | None = None, body: dict | None = None,
    ) -> Any:
        return await _call_gateway(name, endpoint, path_params, params, body)

    gateway_tool.__annotations__["endpoint"] = Literal[tuple(endpoints)]
    listing = "; ".join(f"{key} = {method} /api/{path}" for key, (method, path, _, _) in endpoints.items())
    mcp.add_tool(gateway_tool, name=name, description=(
        f"{description} path_params fills {{placeholders}} in the path, params is the query string, "
        f"body is the JSON payload for write endpoints. Endpoints: {listing}"
    ))


for _gateway_name in _GATEWAY_TOOLS:
    _register_gateway_tool(_gateway_name)


@mcp.tool()
async def submit_direct_receipt_parse(filename: str, content_type: str, file_base64: str) -> dict:
    """Upload a base64 supplier invoice or delivery note (PDF, image, CSV or XLSX, up to 10 MB) for AI line parsing.

    Returns a task_id; poll inventory_query endpoint direct_receipt_parse_status, then create a draft with
    inventory_drafts create_direct_receipt.
    """
    if _COST_PERMISSION not in api._permissions:
        raise PermissionError(f"MCP service user lacks permission: {_COST_PERMISSION}")
    try:
        content = base64.b64decode(file_base64, validate=True)
    except (binascii.Error, ValueError) as exc:
        raise ValueError("file_base64 must be valid base64") from exc
    if not content or len(content) > 10 * 1024 * 1024:
        raise ValueError("file must be non-empty and no larger than 10 MB")
    return await api.request(
        "POST", _INV + "direct-receipts/ai-parse", permission="inventory.purchase",
        files={"file": (Path(filename).name or "receipt", content, content_type)},
    )


def main() -> None:
    logging.basicConfig(level=os.environ.get("LOG_LEVEL", "INFO"))
    import uvicorn

    uvicorn.run(
        mcp_app,
        host=os.environ.get("MCP_HOST", "127.0.0.1"),
        port=int(os.environ.get("MCP_PORT", "8766")),
        log_level=os.environ.get("LOG_LEVEL", "INFO").lower(),
    )


if __name__ == "__main__":
    main()
