from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional, Dict, Any
from datetime import date, datetime, timedelta

from src.utils.db import get_db
from src.marketing.apps.Analytics import service, schema
from src.marketing.apps.Analytics.twitter_analytics import (
    get_twitter_metrics_report, 
    get_latest_performance_score,
    calculate_store_performance_score
)

router = APIRouter(prefix="/analytics", tags=["Twitter Analytics"])

# @router.get("/accounts/{account_id}/metrics", response_model=schema.TwitterAccountMetricsResponse)
# def get_twitter_account_metrics(
#     account_id: int,
#     start_date: date = Query(..., description="Start date for metrics"),
#     end_date: Optional[date] = Query(None, description="End date for metrics (defaults to today)"),
#     db: Session = Depends(get_db)
# ):
#     """
#     Get Twitter account metrics for a specific connected account over a date range.
    
#     This endpoint returns follower counts, impressions, engagement rates and other
#     key performance metrics for a Twitter account in the specified date range.
#     """
#     return service.get_twitter_account_metrics(db, account_id, start_date, end_date)

# @router.get("/accounts/{account_id}/posts", response_model=schema.TwitterPostMetricsResponse)
# def get_twitter_post_metrics(
#     account_id: int,
#     start_date: date = Query(..., description="Start date for metrics"),
#     end_date: Optional[date] = Query(None, description="End date for metrics (defaults to today)"),
#     limit: int = Query(10, description="Maximum number of posts to return"),
#     db: Session = Depends(get_db)
# ):
#     """
#     Get metrics for Twitter posts from a specific connected account.
    
#     This endpoint returns engagement metrics for individual Twitter posts in the specified date range,
#     sorted by engagement rate (highest first).
#     """
#     return service.get_twitter_post_metrics(db, account_id, start_date, end_date, limit)

# @router.get("/accounts/{account_id}/report", response_model=schema.TwitterAnalyticsReportResponse)
# def generate_twitter_analytics_report(
#     account_id: int,
#     start_date: date = Query(..., description="Start date for report"),
#     end_date: Optional[date] = Query(None, description="End date for report (defaults to today)"),
#     db: Session = Depends(get_db)
# ):
#     """
#     Generate a comprehensive analytics report for a Twitter account.
    
#     This endpoint returns a full analytics report including account metrics, top performing posts,
#     audience data, growth metrics, and recommendations for improving performance.
#     """
#     return service.generate_twitter_analytics_report(db, account_id, start_date, end_date)

# @router.get("/accounts/{account_id}/recommendations", response_model=List[str])
# def get_twitter_recommendations(
#     account_id: int,
#     days: int = Query(30, description="Number of days to analyze for recommendations"),
#     db: Session = Depends(get_db)
# ):
#     """
#     Get personalized recommendations for improving Twitter account performance.
    
#     This endpoint analyzes recent account performance and provides actionable
#     recommendations to improve engagement, growth, and content strategy.
#     """
#     end_date = datetime.now().date()
#     start_date = end_date - timedelta(days=days)
    
#     report = service.generate_twitter_analytics_report(db, account_id, start_date, end_date)
#     if not report.success:
#         raise HTTPException(status_code=404, detail=report.message)
    
#     return report.data.recommendations



@router.post("/accounts/metrics-report", response_model=Dict[str, Any])
def get_metrics_report(
    request: schema.MetricsReportRequest,
    db: Session = Depends(get_db)
):
    """
    Generate a comprehensive Twitter metrics report for multiple connected accounts.
    
    This endpoint retrieves stored metrics for the specified accounts and date range,
    and returns a detailed report including aggregated account growth, engagement, and top performing posts.
    """
    return get_twitter_metrics_report(db, request.account_ids, request.start_date, request.end_date)


@router.post("/dashboard-analytics", response_model=schema.SocialMediaAnalyticsResponse)
def get_dashboard_analytics(
    request: schema.MetricsReportRequest,
    db: Session = Depends(get_db)
):
    """
    Get comprehensive social media dashboard analytics for UI display.
    
    This endpoint provides all the metrics needed for the social media analytics dashboard,
    including overall metrics, daily trends, top posts, and engagement data by platform.
    """
    from src.marketing.apps.Analytics.twitter_analytics import get_social_media_dashboard_analytics
    return get_social_media_dashboard_analytics(db, request.account_ids, request.start_date, request.end_date)


@router.get("/accounts/{account_id}/analytics", response_model=Dict[str, Any])
def get_account_analytics(
    account_id: int,
    start_date: date = Query(..., description="Start date for analytics"),
    end_date: Optional[date] = Query(None, description="End date for analytics (defaults to today)"),
    db: Session = Depends(get_db)
):
    """
    Get analytics for a specific social media account.
    
    This endpoint provides account-specific analytics including top tweets,
    engagement metrics, and performance data for individual accounts.
    """
    from src.marketing.apps.Analytics.twitter_analytics import get_account_specific_analytics
    return get_account_specific_analytics(db, account_id, start_date, end_date)


@router.get("/stores/{store_id}/performance-score", response_model=Dict[str, Any])
def get_store_performance_score(
    store_id: int,
    branch_id: Optional[int] = Query(None, description="Optional branch ID"),
    db: Session = Depends(get_db)
):
    """
    Get performance scores for a store.
    
    This endpoint returns:
    - latest_score: The most recent performance score calculated for the store
    - last_12_months: Array of performance scores for the last 12 months
    
    If no score is present for a month, it returns 0 values for that month.
    """
    return get_latest_performance_score(db, store_id, branch_id)


@router.post("/stores/{store_id}/calculate-performance-score", response_model=Dict[str, Any])
def calculate_performance_score(
    store_id: int,
    branch_id: Optional[int] = Query(None, description="Optional branch ID"),
    score_month: Optional[int] = Query(None, description="Month for calculation (1-12, defaults to current month)"),
    score_year: Optional[int] = Query(None, description="Year for calculation (defaults to current year)"),
    db: Session = Depends(get_db)
):
    """
    Calculate and store performance score for a store.
    
    This endpoint calculates the performance score for a specific store and month,
    stores it in the database, and returns the calculated score details.
    """
    return calculate_store_performance_score(db, store_id, branch_id, score_month, score_year)
