from datetime import datetime, timedelta
from pymongo.collection import Collection

async def get_overview_metrics(db, current_user):
    """Return high-level metrics for the tenant."""
    account_id = current_user.get("account_id")
    if not account_id:
        raise ValueError("Account ID not found for current user.")

    users_count = db["users"].count_documents({"account_id": account_id})
    active_subscriptions = db["subscriptions"].count_documents({"account_id": account_id, "status": "active"})
    active_projects = db["projects"].count_documents({"account_id": account_id, "status": "ACTIVE"})

    # Revenue from payments in last 30 days
    now = datetime.utcnow()
    one_month_ago = now - timedelta(days=30)
    pipeline = [
        {"$match": {"account_id": account_id, "status": "paid", "due_date": {"$gte": one_month_ago}}},
        {"$group": {"_id": None, "totalRevenue": {"$sum": "$amount"}}}
    ]
    revenue_result = list(db["payments"].aggregate(pipeline))
    total_revenue = revenue_result[0]["totalRevenue"] if revenue_result else 0

    return {
        "users_count": users_count,
        "active_subscriptions": active_subscriptions,
        "active_projects": active_projects,
        "total_revenue": total_revenue,
        "last_updated": now.isoformat()
    }

async def get_usage_trends(db, current_user, start_date: datetime, end_date: datetime):
    """Return daily usage metrics (e.g., user logins) grouped by day."""
    account_id = current_user.get("account_id")
    pipeline = [
        {"$match": {
            "account_id": account_id,
            "login_date": {"$gte": start_date, "$lte": end_date}
        }},
        {"$group": {
            "_id": {"$dateToString": {"format": "%Y-%m-%d", "date": "$login_date"}},
            "daily_logins": {"$sum": 1}
        }},
        {"$sort": {"_id": 1}}
    ]
    usage = list(db["user_logins"].aggregate(pipeline))
    return usage

async def get_financial_trends(db, current_user, start_date: datetime, end_date: datetime):
    """Return revenue trends grouped by day."""
    account_id = current_user.get("account_id")
    pipeline = [
        {"$match": {
            "account_id": account_id,
            "status": "paid",
            "due_date": {"$gte": start_date, "$lte": end_date}
        }},
        {"$group": {
            "_id": {"$dateToString": {"format": "%Y-%m-%d", "date": "$due_date"}},
            "daily_revenue": {"$sum": "$amount"}
        }},
        {"$sort": {"_id": 1}}
    ]
    revenue_trends = list(db["payments"].aggregate(pipeline))
    return revenue_trends

async def search_accounts(db, search_query: str, skip: int, limit: int):
    """Perform account search with pagination."""
    query = {"$or": [
        {"account_name": {"$regex": search_query, "$options": "i"}},
        {"email": {"$regex": search_query, "$options": "i"}}
    ]}
    accounts_cursor = db["accounts"].find(query).skip(skip).limit(limit)
    accounts = list(accounts_cursor)
    total_count = db["accounts"].count_documents(query)
    # Convert ObjectIds and dates as needed here...
    return {"total_count": total_count, "accounts": accounts}

async def get_dashboard_metrics_service(db, current_user, start_date: datetime = None, end_date: datetime = None):
    """Aggregate dashboard data including overview, usage, and financial trends."""
    # Default to last 30 days if no dates are provided
    now = datetime.utcnow()
    if start_date is None:
        start_date = now - timedelta(days=30)
    if end_date is None:
        end_date = now

    overview = await get_overview_metrics(db, current_user)
    usage = await get_usage_trends(db, current_user, start_date, end_date)
    revenue = await get_financial_trends(db, current_user, start_date, end_date)

    dashboard = {
        "overview": overview,
        "usage_trends": usage,
        "revenue_trends": revenue,
        "date_range": {"start": start_date.isoformat(), "end": end_date.isoformat()}
    }
    return dashboard
