# services/forecasting/app/api/analytics.py
"""
Forecasting Analytics API - Reporting, statistics, and insights
"""

import structlog
from fastapi import APIRouter, Depends, HTTPException, status, Query, Path
from datetime import date
from typing import Optional

from app.services.prediction_service import PredictionService
from shared.database.base import create_database_manager
from app.core.config import settings
from shared.routing import RouteBuilder
from shared.auth.access_control import analytics_tier_required

route_builder = RouteBuilder('forecasting')
logger = structlog.get_logger()
router = APIRouter(tags=["forecasting-analytics"])


def get_enhanced_prediction_service():
    """Dependency injection for enhanced PredictionService"""
    database_manager = create_database_manager(settings.DATABASE_URL, "forecasting-service")
    return PredictionService(database_manager)


@router.get(
    route_builder.build_analytics_route("predictions-performance")
)
@analytics_tier_required
async def get_predictions_performance(
    tenant_id: str = Path(..., description="Tenant ID"),
    start_date: Optional[date] = Query(None),
    end_date: Optional[date] = Query(None),
    prediction_service: PredictionService = Depends(get_enhanced_prediction_service)
):
    """Get predictions performance analytics (Professional+ tier required)"""
    try:
        logger.info("Getting predictions performance", tenant_id=tenant_id)

        performance = await prediction_service.get_performance_metrics(
            tenant_id=tenant_id,
            start_date=start_date,
            end_date=end_date
        )

        return performance

    except Exception as e:
        logger.error("Failed to get predictions performance", error=str(e), tenant_id=tenant_id)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="Failed to retrieve predictions performance"
        )
