# app/modules/core/routes/api/store_menu.py
"""
Store menu rendering endpoint.

Provides the dynamic sidebar menu for the store portal:
- GET /menu/render/store - Get rendered store menu for current user

Menu sections are driven by module definitions (FrontendType.STORE).
Only modules enabled on the store's platform will appear in the sidebar.
Visibility is controlled by AdminMenuConfig records for the platform.
"""

import logging
from typing import Any

from fastapi import APIRouter, Depends, Request
from pydantic import BaseModel
from sqlalchemy.orm import Session

from app.api.deps import get_current_store_api, get_user_permissions
from app.core.database import get_db
from app.modules.core.services.menu_service import menu_service
from app.modules.enums import FrontendType
from app.modules.tenancy.schemas.auth import UserContext
from app.modules.tenancy.services.store_service import store_service
from app.utils.i18n import translate

logger = logging.getLogger(__name__)

store_menu_router = APIRouter(prefix="/menu")


# =============================================================================
# Schemas
# =============================================================================


class MenuSectionResponse(BaseModel):
    """Menu section for rendering."""

    id: str
    label: str | None = None
    items: list[dict[str, Any]]


class RenderedMenuResponse(BaseModel):
    """Rendered menu for frontend."""

    frontend_type: str
    sections: list[MenuSectionResponse]


# =============================================================================
# Helpers
# =============================================================================


def _translate_label(label_key: str | None, language: str) -> str | None:
    """Translate a label key, falling back to a readable version of the key."""
    if not label_key:
        return None

    translated = translate(label_key, language=language)

    # If translation returned the key itself, create a readable fallback
    if translated == label_key:
        parts = label_key.split(".")
        last_part = parts[-1]
        return last_part.replace("_", " ").title()

    return translated


# =============================================================================
# Endpoint
# =============================================================================


@store_menu_router.get("/render/store", response_model=RenderedMenuResponse)
async def get_rendered_store_menu(
    request: Request,
    db: Session = Depends(get_db),
    current_user: UserContext = Depends(get_current_store_api),
    user_perms: list = Depends(get_user_permissions),
):
    """
    Get the rendered store menu for the current user.

    Returns the filtered menu structure based on:
    - Modules enabled on the store's platform
    - AdminMenuConfig visibility for the platform
    - Store code for URL placeholder replacement
    - User permissions (items with requires_permission are hidden if user lacks it)

    Used by the store frontend to render the sidebar dynamically.
    """
    # Get the store from the JWT token's store context
    store = store_service.get_store_by_id(db, current_user.token_store_id)

    # Platform from JWT (set at login from URL context), fall back to DB for old tokens
    platform_id = current_user.token_platform_id
    if platform_id is None:
        platform_id = menu_service.get_store_fallback_platform_id(db, store.id)

    # Get filtered menu with platform visibility, store_code, and permission filtering
    menu = menu_service.get_menu_for_rendering(
        db=db,
        frontend_type=FrontendType.STORE,
        platform_id=platform_id,
        store_code=store.subdomain,
        user_permissions=user_perms,
    )

    # Resolve language
    language = current_user.preferred_language or getattr(
        request.state, "language", "en"
    )

    # Translate section and item labels
    sections = []
    for section in menu:
        translated_items = []
        for item in section.items:
            translated_items.append(
                {
                    "id": item.id,
                    "label": _translate_label(item.label_key, language),
                    "icon": item.icon,
                    "url": item.route,
                }
            )

        sections.append(
            MenuSectionResponse(
                id=section.id,
                label=_translate_label(section.label_key, language),
                items=translated_items,
            )
        )

    return RenderedMenuResponse(
        frontend_type=FrontendType.STORE.value,
        sections=sections,
    )
