# app/modules/core/routes/api/admin_dashboard.py
"""
Admin dashboard and statistics endpoints.

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.

Dashboard widgets are collected via the WidgetAggregator service, which discovers
DashboardWidgetProvider implementations from all enabled modules.
"""

import logging
from typing import Any

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

from app.api.deps import get_current_admin_api
from app.core.database import get_db
from app.modules.contracts.widgets import BreakdownWidget, ListWidget, WidgetListItem
from app.modules.core.schemas.dashboard import (
    AdminDashboardResponse,
    ImportStatsResponse,
    MarketplaceStatsResponse,
    OrderStatsBasicResponse,
    PlatformStatsResponse,
    ProductStatsResponse,
    StatsResponse,
    StoreStatsResponse,
    UserStatsResponse,
)
from app.modules.core.services.stats_aggregator import stats_aggregator
from app.modules.core.services.widget_aggregator import widget_aggregator
from app.modules.tenancy.schemas.auth import UserContext

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


def _get_platform_id(request: Request, current_admin: UserContext) -> int:
    """
    Get platform_id from available sources in priority order.

    Priority:
    1. JWT token (token_platform_id) - set when admin selects a platform
    2. Request state (set by PlatformContextMiddleware) - for page routes
    3. First accessible platform (for platform admins)
    4. Fallback to 1 (for super admins with global access)

    Returns:
        Platform ID to use for queries
    """
    # 1. From JWT token (most authoritative for API routes)
    if current_admin.token_platform_id:
        return current_admin.token_platform_id

    # 2. From request state (set by PlatformContextMiddleware)
    platform = getattr(request.state, "platform", None)
    if platform:
        return platform.id

    # 3. For platform admins, use their first accessible platform
    if current_admin.accessible_platform_ids:
        return current_admin.accessible_platform_ids[0]

    # 4. Fallback for super admins (global access)
    return 1


def _widget_list_item_to_dict(item: WidgetListItem) -> dict[str, Any]:
    """Convert a WidgetListItem to a dictionary for API response."""
    return {
        "id": item.id,
        "title": item.title,
        "subtitle": item.subtitle,
        "status": item.status,
        "timestamp": item.timestamp,
        "url": item.url,
        **item.metadata,
    }


def _get_list_widget_items(
    widgets: dict[str, list], key: str
) -> list[dict[str, Any]]:
    """Extract items from a list widget by key, searching all categories."""
    for category_widgets in widgets.values():
        for widget in category_widgets:
            if widget.key == key and isinstance(widget.data, ListWidget):
                return [_widget_list_item_to_dict(item) for item in widget.data.items]
    return []


@admin_dashboard_router.get("", response_model=AdminDashboardResponse)
def get_admin_dashboard(
    request: Request,
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """Get admin dashboard with platform statistics (Admin only)."""
    platform_id = _get_platform_id(request, current_admin)

    # Get flat metrics from all enabled modules
    metrics = stats_aggregator.get_admin_stats_flat(db=db, platform_id=platform_id)

    # Get aggregated widgets from all enabled modules
    widgets = widget_aggregator.get_admin_dashboard_widgets(db=db, platform_id=platform_id)

    return AdminDashboardResponse(
        platform={
            "name": "Multi-Tenant Ecommerce Platform",
            "version": "1.0.0",
        },
        users=UserStatsResponse(
            total_users=int(metrics.get("tenancy.total_users", 0)),
            active_users=int(metrics.get("tenancy.active_users", 0)),
            inactive_users=int(metrics.get("tenancy.inactive_users", 0)),
            admin_users=int(metrics.get("tenancy.admin_users", 0)),
            activation_rate=float(metrics.get("tenancy.user_activation_rate", 0)),
        ),
        stores=StoreStatsResponse(
            total=int(metrics.get("tenancy.total_stores", 0)),
            verified=int(metrics.get("tenancy.verified_stores", 0)),
            pending=int(metrics.get("tenancy.pending_stores", 0)),
            inactive=int(metrics.get("tenancy.inactive_stores", 0)),
        ),
        recent_stores=_get_list_widget_items(widgets, "tenancy.recent_stores"),
        recent_imports=_get_list_widget_items(widgets, "marketplace.recent_imports"),
    )


@admin_dashboard_router.get("/stats", response_model=StatsResponse)
def get_comprehensive_stats(
    request: Request,
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """Get comprehensive platform statistics (Admin only)."""
    platform_id = _get_platform_id(request, current_admin)

    # Get flat metrics from all enabled modules
    metrics = stats_aggregator.get_admin_stats_flat(db=db, platform_id=platform_id)

    return StatsResponse(
        total_products=int(metrics.get("catalog.total_products", 0)),
        unique_brands=int(metrics.get("marketplace.unique_brands", 0)),
        unique_categories=0,  # TODO: Add category tracking
        unique_marketplaces=int(metrics.get("marketplace.unique_marketplaces", 0)),
        unique_stores=int(metrics.get("tenancy.total_stores", 0)),
        total_inventory_entries=int(metrics.get("inventory.entries", 0)),
        total_inventory_quantity=int(metrics.get("inventory.total_quantity", 0)),
    )


@admin_dashboard_router.get(
    "/stats/marketplace", response_model=list[MarketplaceStatsResponse]
)
def get_marketplace_stats(
    request: Request,
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """Get statistics broken down by marketplace (Admin only).

    Uses the widget_aggregator to get marketplace breakdown data from the
    marketplace module's WidgetProvider, avoiding cross-module violations.
    """
    platform_id = _get_platform_id(request, current_admin)

    # Get widgets from marketplace module via aggregator
    widgets = widget_aggregator.get_admin_dashboard_widgets(db=db, platform_id=platform_id)

    # Extract marketplace breakdown widget
    marketplace_widgets = widgets.get("marketplace", [])
    for widget in marketplace_widgets:
        if widget.key == "marketplace.breakdown" and isinstance(widget.data, BreakdownWidget):
            # Transform breakdown items to MarketplaceStatsResponse
            return [
                MarketplaceStatsResponse(
                    marketplace=item.label,
                    total_products=int(item.value),
                    unique_stores=int(item.secondary_value or 0),
                    unique_brands=0,  # Not included in breakdown widget
                )
                for item in widget.data.items
            ]

    # No breakdown widget found
    return []


@admin_dashboard_router.get("/stats/platform", response_model=PlatformStatsResponse)
def get_platform_statistics(
    request: Request,
    db: Session = Depends(get_db),
    current_admin: UserContext = Depends(get_current_admin_api),
):
    """Get comprehensive platform statistics (Admin only)."""
    platform_id = _get_platform_id(request, current_admin)

    # Get flat metrics from all enabled modules
    metrics = stats_aggregator.get_admin_stats_flat(db=db, platform_id=platform_id)

    return PlatformStatsResponse(
        users=UserStatsResponse(
            total_users=int(metrics.get("tenancy.total_users", 0)),
            active_users=int(metrics.get("tenancy.active_users", 0)),
            inactive_users=int(metrics.get("tenancy.inactive_users", 0)),
            admin_users=int(metrics.get("tenancy.admin_users", 0)),
            activation_rate=float(metrics.get("tenancy.user_activation_rate", 0)),
        ),
        stores=StoreStatsResponse(
            total=int(metrics.get("tenancy.total_stores", 0)),
            verified=int(metrics.get("tenancy.verified_stores", 0)),
            pending=int(metrics.get("tenancy.pending_stores", 0)),
            inactive=int(metrics.get("tenancy.inactive_stores", 0)),
        ),
        products=ProductStatsResponse(
            total_products=int(metrics.get("catalog.total_products", 0)),
            active_products=int(metrics.get("catalog.active_products", 0)),
            out_of_stock=0,  # TODO: Implement
        ),
        orders=OrderStatsBasicResponse(
            total_orders=int(metrics.get("orders.total", 0)),
            pending_orders=0,  # TODO: Implement status tracking
            completed_orders=0,  # TODO: Implement status tracking
        ),
        imports=ImportStatsResponse(
            total=int(metrics.get("marketplace.total_imports", 0)),
            pending=int(metrics.get("marketplace.pending_imports", 0)),
            processing=int(metrics.get("marketplace.processing_imports", 0)),
            completed=int(metrics.get("marketplace.successful_imports", 0)),
            failed=int(metrics.get("marketplace.failed_imports", 0)),
            success_rate=float(metrics.get("marketplace.success_rate", 0)),
        ),
    )
