from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import Optional
from ...shared.config.database import get_db
from ...security.middleware.auth import authorize_roles, get_current_user
from ...auth.models.user import User
from ..services.analytics_service import AnalyticsService

router = APIRouter(prefix='/analytics', tags=['analytics'])

# ==================== REVENUE ANALYTICS ====================

@router.get('/revenue/revpar')
async def get_revpar(
    start_date: Optional[str] = Query(None, alias='from'),
    end_date: Optional[str] = Query(None, alias='to'),
    current_user: User = Depends(authorize_roles('admin', 'staff', 'accountant')),
    db: Session = Depends(get_db)
):
    """Get RevPAR (Revenue Per Available Room)"""
    try:
        start, end = AnalyticsService.parse_date_range(start_date, end_date)
        result = AnalyticsService.get_revpar(db, start, end)
        return {'status': 'success', 'data': result}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get('/revenue/adr')
async def get_adr(
    start_date: Optional[str] = Query(None, alias='from'),
    end_date: Optional[str] = Query(None, alias='to'),
    current_user: User = Depends(authorize_roles('admin', 'staff', 'accountant')),
    db: Session = Depends(get_db)
):
    """Get ADR (Average Daily Rate)"""
    try:
        start, end = AnalyticsService.parse_date_range(start_date, end_date)
        result = AnalyticsService.get_adr(db, start, end)
        return {'status': 'success', 'data': result}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get('/revenue/occupancy')
async def get_occupancy_rate(
    start_date: Optional[str] = Query(None, alias='from'),
    end_date: Optional[str] = Query(None, alias='to'),
    current_user: User = Depends(authorize_roles('admin', 'staff', 'accountant')),
    db: Session = Depends(get_db)
):
    """Get Occupancy Rate"""
    try:
        start, end = AnalyticsService.parse_date_range(start_date, end_date)
        result = AnalyticsService.get_occupancy_rate(db, start, end)
        return {'status': 'success', 'data': result}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get('/revenue/forecast')
async def get_revenue_forecast(
    days: int = Query(30, ge=1, le=365),
    current_user: User = Depends(authorize_roles('admin', 'staff', 'accountant')),
    db: Session = Depends(get_db)
):
    """Get Revenue Forecast"""
    try:
        result = AnalyticsService.get_revenue_forecast(db, days)
        return {'status': 'success', 'data': result}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get('/revenue/market-penetration')
async def get_market_penetration(
    start_date: Optional[str] = Query(None, alias='from'),
    end_date: Optional[str] = Query(None, alias='to'),
    current_user: User = Depends(authorize_roles('admin', 'staff', 'accountant')),
    db: Session = Depends(get_db)
):
    """Get Market Penetration Analysis"""
    try:
        start, end = AnalyticsService.parse_date_range(start_date, end_date)
        result = AnalyticsService.get_market_penetration(db, start, end)
        return {'status': 'success', 'data': result}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# ==================== OPERATIONAL ANALYTICS ====================

@router.get('/operational/staff-performance')
async def get_staff_performance(
    start_date: Optional[str] = Query(None, alias='from'),
    end_date: Optional[str] = Query(None, alias='to'),
    current_user: User = Depends(authorize_roles('admin', 'staff')),
    db: Session = Depends(get_db)
):
    """Get Staff Performance Metrics"""
    try:
        start, end = AnalyticsService.parse_date_range(start_date, end_date)
        result = AnalyticsService.get_staff_performance(db, start, end)
        return {'status': 'success', 'data': result}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get('/operational/service-usage')
async def get_service_usage_analytics(
    start_date: Optional[str] = Query(None, alias='from'),
    end_date: Optional[str] = Query(None, alias='to'),
    current_user: User = Depends(authorize_roles('admin', 'staff', 'accountant')),
    db: Session = Depends(get_db)
):
    """Get Service Usage Analytics"""
    try:
        start, end = AnalyticsService.parse_date_range(start_date, end_date)
        result = AnalyticsService.get_service_usage_analytics(db, start, end)
        return {'status': 'success', 'data': result}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get('/operational/efficiency')
async def get_operational_efficiency(
    start_date: Optional[str] = Query(None, alias='from'),
    end_date: Optional[str] = Query(None, alias='to'),
    current_user: User = Depends(authorize_roles('admin', 'staff', 'accountant')),
    db: Session = Depends(get_db)
):
    """Get Operational Efficiency Metrics"""
    try:
        start, end = AnalyticsService.parse_date_range(start_date, end_date)
        result = AnalyticsService.get_operational_efficiency(db, start, end)
        return {'status': 'success', 'data': result}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# ==================== GUEST ANALYTICS ====================

@router.get('/guest/lifetime-value')
async def get_guest_lifetime_value(
    start_date: Optional[str] = Query(None, alias='from'),
    end_date: Optional[str] = Query(None, alias='to'),
    current_user: User = Depends(authorize_roles('admin', 'staff', 'accountant')),
    db: Session = Depends(get_db)
):
    """Get Guest Lifetime Value Analysis"""
    try:
        start, end = AnalyticsService.parse_date_range(start_date, end_date)
        result = AnalyticsService.get_guest_lifetime_value(db, start, end)
        return {'status': 'success', 'data': result}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get('/guest/acquisition-cost')
async def get_customer_acquisition_cost(
    start_date: Optional[str] = Query(None, alias='from'),
    end_date: Optional[str] = Query(None, alias='to'),
    current_user: User = Depends(authorize_roles('admin', 'staff', 'accountant')),
    db: Session = Depends(get_db)
):
    """Get Customer Acquisition Cost Analysis"""
    try:
        start, end = AnalyticsService.parse_date_range(start_date, end_date)
        result = AnalyticsService.get_customer_acquisition_cost(db, start, end)
        return {'status': 'success', 'data': result}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get('/guest/repeat-rate')
async def get_repeat_guest_rate(
    start_date: Optional[str] = Query(None, alias='from'),
    end_date: Optional[str] = Query(None, alias='to'),
    current_user: User = Depends(authorize_roles('admin', 'staff', 'accountant')),
    db: Session = Depends(get_db)
):
    """Get Repeat Guest Rate"""
    try:
        start, end = AnalyticsService.parse_date_range(start_date, end_date)
        result = AnalyticsService.get_repeat_guest_rate(db, start, end)
        return {'status': 'success', 'data': result}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get('/guest/satisfaction-trends')
async def get_guest_satisfaction_trends(
    start_date: Optional[str] = Query(None, alias='from'),
    end_date: Optional[str] = Query(None, alias='to'),
    current_user: User = Depends(authorize_roles('admin', 'staff', 'accountant')),
    db: Session = Depends(get_db)
):
    """Get Guest Satisfaction Trends"""
    try:
        start, end = AnalyticsService.parse_date_range(start_date, end_date)
        result = AnalyticsService.get_guest_satisfaction_trends(db, start, end)
        return {'status': 'success', 'data': result}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# ==================== FINANCIAL ANALYTICS ====================

@router.get('/financial/profit-loss')
async def get_profit_loss(
    start_date: Optional[str] = Query(None, alias='from'),
    end_date: Optional[str] = Query(None, alias='to'),
    current_user: User = Depends(authorize_roles('admin', 'accountant')),
    db: Session = Depends(get_db)
):
    """Get Profit & Loss Report"""
    try:
        start, end = AnalyticsService.parse_date_range(start_date, end_date)
        result = AnalyticsService.get_profit_loss(db, start, end)
        return {'status': 'success', 'data': result}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get('/financial/payment-methods')
async def get_payment_method_analytics(
    start_date: Optional[str] = Query(None, alias='from'),
    end_date: Optional[str] = Query(None, alias='to'),
    current_user: User = Depends(authorize_roles('admin', 'staff', 'accountant')),
    db: Session = Depends(get_db)
):
    """Get Payment Method Analytics"""
    try:
        start, end = AnalyticsService.parse_date_range(start_date, end_date)
        result = AnalyticsService.get_payment_method_analytics(db, start, end)
        return {'status': 'success', 'data': result}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get('/financial/refunds')
async def get_refund_analysis(
    start_date: Optional[str] = Query(None, alias='from'),
    end_date: Optional[str] = Query(None, alias='to'),
    current_user: User = Depends(authorize_roles('admin', 'accountant')),
    db: Session = Depends(get_db)
):
    """Get Refund Analysis"""
    try:
        start, end = AnalyticsService.parse_date_range(start_date, end_date)
        result = AnalyticsService.get_refund_analysis(db, start, end)
        return {'status': 'success', 'data': result}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# ==================== COMPREHENSIVE ANALYTICS ====================

@router.get('/comprehensive')
async def get_comprehensive_analytics(
    start_date: Optional[str] = Query(None, alias='from'),
    end_date: Optional[str] = Query(None, alias='to'),
    include_revenue: bool = Query(True),
    include_operational: bool = Query(True),
    include_guest: bool = Query(True),
    include_financial: bool = Query(True),
    current_user: User = Depends(authorize_roles('admin', 'staff', 'accountant')),
    db: Session = Depends(get_db)
):
    """Get Comprehensive Analytics across all categories"""
    try:
        result = AnalyticsService.get_comprehensive_analytics(
            db,
            start_date,
            end_date,
            include_revenue,
            include_operational,
            include_guest,
            include_financial
        )
        return {'status': 'success', 'data': result}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

