# app/modules/core/routes/api/store_dashboard.py
"""
Store dashboard and statistics endpoints.

Store Context: Uses token_store_id from JWT token (authenticated store API pattern).
The get_current_store_api dependency guarantees token_store_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_store_api, require_platform
from app.core.database import get_db
from app.modules.core.schemas.dashboard import (
    StoreCustomerStats,
    StoreDashboardStatsResponse,
    StoreInfo,
    StoreOrderStats,
    StoreProductStats,
    StoreRevenueStats,
)
from app.modules.core.services.onboarding_aggregator import onboarding_aggregator
from app.modules.core.services.stats_aggregator import stats_aggregator
from app.modules.tenancy.exceptions import StoreNotActiveException
from app.modules.tenancy.schemas.auth import UserContext
from app.modules.tenancy.services.store_service import store_service

store_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


@store_dashboard_router.get("/stats", response_model=StoreDashboardStatsResponse)
def get_store_dashboard_stats(
    request: Request,
    current_user: UserContext = Depends(get_current_store_api),
    platform=Depends(require_platform),
    db: Session = Depends(get_db),
):
    """
    Get store-specific dashboard statistics.

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

    Store is determined from the JWT token (store_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.
    """
    store_id = current_user.token_store_id

    # Get store object (raises StoreNotFoundException if not found)
    store = store_service.get_store_by_id(db, store_id)

    if not store.is_active:
        raise StoreNotActiveException(store.store_code)

    platform_id = platform.id
    metrics = stats_aggregator.get_store_dashboard_stats(
        db=db,
        store_id=store_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 StoreDashboardStatsResponse(
        store=StoreInfo(
            id=store.id,
            name=store.name,
            store_code=store.store_code,
        ),
        products=StoreProductStats(
            total=int(total_products),
            active=int(active_products),
        ),
        orders=StoreOrderStats(
            total=int(total_orders),
            pending=int(pending_orders),
            completed=int(completed_orders),
        ),
        customers=StoreCustomerStats(
            total=int(total_customers),
            active=int(active_customers),
        ),
        revenue=StoreRevenueStats(
            total=float(total_revenue),
            this_month=float(revenue_this_month),
        ),
    )


@store_dashboard_router.get("/onboarding")
def get_onboarding_status(
    request: Request,
    current_user: UserContext = Depends(get_current_store_api),
    platform=Depends(require_platform),
    db: Session = Depends(get_db),
):
    """
    Get onboarding checklist status for the current store.

    Returns steps from all enabled modules with completion status,
    progress percentage, and whether all steps are completed.
    """
    store_id = current_user.token_store_id
    store = store_service.get_store_by_id(db, store_id)

    summary = onboarding_aggregator.get_onboarding_summary(
        db=db,
        store_id=store_id,
        platform_id=platform.id,
        store_code=store.store_code,
    )
    summary["is_owner"] = current_user.role == "merchant_owner"
    return summary
