# app/modules/analytics/routes/pages/vendor.py
"""
Analytics Vendor Page Routes (HTML rendering).

Vendor pages for analytics dashboard.
"""

import logging

from fastapi import APIRouter, Depends, Path, Request
from fastapi.responses import HTMLResponse
from sqlalchemy.orm import Session

from app.api.deps import get_current_vendor_from_cookie_or_header, get_db
from app.modules.core.services.platform_settings_service import platform_settings_service  # noqa: MOD-004 - shared platform service
from app.templates_config import templates
from app.modules.tenancy.models import User
from app.modules.tenancy.models import Vendor

logger = logging.getLogger(__name__)

router = APIRouter()


# ============================================================================
# HELPER: Build Vendor Dashboard Context
# ============================================================================


def get_vendor_context(
    request: Request,
    db: Session,
    current_user: User,
    vendor_code: str,
    **extra_context,
) -> dict:
    """
    Build template context for vendor dashboard pages.

    Resolves locale/currency using the platform settings service with
    vendor override support.
    """
    # Load vendor from database
    vendor = db.query(Vendor).filter(Vendor.subdomain == vendor_code).first()

    # Get platform defaults
    platform_config = platform_settings_service.get_storefront_config(db)

    # Resolve with vendor override
    storefront_locale = platform_config["locale"]
    storefront_currency = platform_config["currency"]

    if vendor and vendor.storefront_locale:
        storefront_locale = vendor.storefront_locale

    context = {
        "request": request,
        "user": current_user,
        "vendor": vendor,
        "vendor_code": vendor_code,
        "storefront_locale": storefront_locale,
        "storefront_currency": storefront_currency,
        **extra_context,
    }

    return context


# ============================================================================
# ANALYTICS PAGE
# ============================================================================


@router.get(
    "/{vendor_code}/analytics", response_class=HTMLResponse, include_in_schema=False
)
async def vendor_analytics_page(
    request: Request,
    vendor_code: str = Path(..., description="Vendor code"),
    current_user: User = Depends(get_current_vendor_from_cookie_or_header),
    db: Session = Depends(get_db),
):
    """
    Render analytics and reports page.
    JavaScript loads analytics data via API.
    """
    return templates.TemplateResponse(
        "analytics/vendor/analytics.html",
        get_vendor_context(request, db, current_user, vendor_code),
    )
