# app/modules/core/routes/api/vendor_dashboard.py
"""
Vendor dashboard and statistics endpoints.

Vendor Context: Uses token_vendor_id from JWT token (authenticated vendor API pattern).
The get_current_vendor_api dependency guarantees token_vendor_id is present.

This module uses the StatsAggregator service from core to collect metrics from all
enabled modules. Each module provides its own metrics via the MetricsProvider protocol.
"""

import logging

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

from app.api.deps import get_current_vendor_api
from app.core.database import get_db
from app.modules.core.schemas.dashboard import (
    VendorCustomerStats,
    VendorDashboardStatsResponse,
    VendorInfo,
    VendorOrderStats,
    VendorProductStats,
    VendorRevenueStats,
)
from app.modules.core.services.stats_aggregator import stats_aggregator
from app.modules.tenancy.exceptions import VendorNotActiveException
from app.modules.tenancy.services.vendor_service import vendor_service
from models.schema.auth import UserContext

vendor_dashboard_router = APIRouter(prefix="/dashboard")
logger = logging.getLogger(__name__)


def _extract_metric_value(
    metrics: dict[str, list], category: str, key: str, default: int | float = 0
) -> int | float:
    """Extract a specific metric value from categorized metrics."""
    if category not in metrics:
        return default
    for metric in metrics[category]:
        if metric.key == key:
            return metric.value
    return default


@vendor_dashboard_router.get("/stats", response_model=VendorDashboardStatsResponse)
def get_vendor_dashboard_stats(
    request: Request,
    current_user: UserContext = Depends(get_current_vendor_api),
    db: Session = Depends(get_db),
):
    """
    Get vendor-specific dashboard statistics.

    Returns statistics for the current vendor only:
    - Total products in catalog
    - Total orders
    - Total customers
    - Revenue metrics

    Vendor is determined from the JWT token (vendor_id claim).
    Requires Authorization header (API endpoint).

    Statistics are aggregated from all enabled modules via the MetricsProvider protocol.
    Each module provides its own metrics, which are combined here for the dashboard.
    """
    vendor_id = current_user.token_vendor_id

    # Get vendor object (raises VendorNotFoundException if not found)
    vendor = vendor_service.get_vendor_by_id(db, vendor_id)

    if not vendor.is_active:
        raise VendorNotActiveException(vendor.vendor_code)

    # Get aggregated metrics from all enabled modules
    # Get platform_id from request context (set by PlatformContextMiddleware)
    platform = getattr(request.state, "platform", None)
    platform_id = platform.id if platform else 1
    metrics = stats_aggregator.get_vendor_dashboard_stats(
        db=db,
        vendor_id=vendor_id,
        platform_id=platform_id,
    )

    # Extract metrics from each category
    # Product metrics (from catalog module)
    total_products = _extract_metric_value(metrics, "catalog", "catalog.total_products", 0)
    active_products = _extract_metric_value(metrics, "catalog", "catalog.active_products", 0)

    # Order metrics (from orders module)
    total_orders = _extract_metric_value(metrics, "orders", "orders.total", 0)
    pending_orders = 0  # TODO: Add when status tracking is implemented
    completed_orders = 0  # TODO: Add when status tracking is implemented

    # Customer metrics (from customers module)
    total_customers = _extract_metric_value(metrics, "customers", "customers.total", 0)
    active_customers = 0  # TODO: Add when activity tracking is implemented

    # Revenue metrics (from orders module)
    total_revenue = _extract_metric_value(metrics, "orders", "orders.total_revenue", 0)
    revenue_this_month = _extract_metric_value(metrics, "orders", "orders.revenue_period", 0)

    return VendorDashboardStatsResponse(
        vendor=VendorInfo(
            id=vendor.id,
            name=vendor.name,
            vendor_code=vendor.vendor_code,
        ),
        products=VendorProductStats(
            total=int(total_products),
            active=int(active_products),
        ),
        orders=VendorOrderStats(
            total=int(total_orders),
            pending=int(pending_orders),
            completed=int(completed_orders),
        ),
        customers=VendorCustomerStats(
            total=int(total_customers),
            active=int(active_customers),
        ),
        revenue=VendorRevenueStats(
            total=float(total_revenue),
            this_month=float(revenue_this_month),
        ),
    )
