"""Standalone, tenant-scoped MCP gateway for the OmniStore catalogue API."""
from __future__ import annotations

import hmac
import logging
import os
import time
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Any

import httpx
from mcp.server.fastmcp import FastMCP
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
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()


class ApiKeyMiddleware(BaseHTTPMiddleware):
    """Protect the standalone MCP endpoint using its own Bearer key."""

    async def dispatch(self, request: Request, call_next):
        expected = os.environ.get("MCP_API_KEY", "")
        header = request.headers.get("authorization", "")
        supplied = header[7:] if header.lower().startswith("bearer ") else ""
        if not expected or not supplied or not hmac.compare_digest(expected, supplied):
            return JSONResponse({"error": "Unauthorized"}, status_code=401)
        return await call_next(request)


class OmniStoreApi:
    """HTTP client that logs in as one fixed tenant service user."""

    def __init__(self) -> None:
        self.base_url = ""
        self.email = ""
        self.password = ""
        self.store_domain = ""
        self.user_id = 0
        self.tenant_id = 0
        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.base_url = os.environ["MCP_BACKEND_URL"].rstrip("/")
        self.email = os.environ["MCP_BACKEND_EMAIL"]
        self.password = os.environ["MCP_BACKEND_PASSWORD"]
        self.store_domain = os.environ["MCP_STORE_DOMAIN"]
        self.user_id = int(os.environ["MCP_USER_ID"])
        self.tenant_id = int(os.environ["MCP_TENANT_ID"])
        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")
        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 MCP_USER_ID/MCP_TENANT_ID")
        self._permissions = set(permission_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,
    ) -> 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,
                headers={"Authorization": f"Bearer {self._token}"},
            )
            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 = OmniStoreApi()


@asynccontextmanager
async def lifespan(_server: FastMCP):
    required = (
        "MCP_API_KEY", "MCP_BACKEND_URL", "MCP_BACKEND_EMAIL",
        "MCP_BACKEND_PASSWORD", "MCP_STORE_DOMAIN", "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))
    await api.start()
    try:
        yield {}
    finally:
        await api.close()


mcp = FastMCP(
    "SME OmniStore Product Catalogue",
    instructions=(
        "Manage product catalogue data for the single tenant configured on this server. "
        "The tenant cannot be selected in tool arguments. Inventory quantities are not writable. "
        "Before replacing pricing rules, read the latest price_rules_version."
    ),
    host=os.environ.get("MCP_HOST", "127.0.0.1"),
    port=int(os.environ.get("MCP_PORT", "8766")),
    streamable_http_path="/mcp",
    # Keep one backend login/permission context per MCP session. The API client
    # is shared by registered tools, so per-request stateless lifespans can race
    # while handling initialize/notifications/tools/list requests.
    stateless_http=False,
    json_response=True,
    lifespan=lifespan,
)
mcp_app = mcp.streamable_http_app()
mcp_app.add_middleware(ApiKeyMiddleware)


@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 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 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)


def main() -> None:
    logging.basicConfig(level=os.environ.get("LOG_LEVEL", "INFO"))
    mcp.run(transport="streamable-http")


if __name__ == "__main__":
    main()
