import logging
from typing import List, Union
from datetime import datetime
from sqlalchemy.ext.asyncio import AsyncSession
from app.models import Expense as ExpenseModel, Settlement as SettlementModel
from app.crud import expense as crud_expense, settlement as crud_settlement

logger = logging.getLogger(__name__)

async def get_user_financial_activity(
    db: AsyncSession, user_id: int
) -> List[Union[ExpenseModel, SettlementModel]]:
    """
    Retrieves and merges all financial activities (expenses and settlements) for a user.
    The combined list is sorted by date.
    """
    # Fetch all accessible expenses
    expenses = await crud_expense.get_user_accessible_expenses(db, user_id=user_id, limit=200) # Using a generous limit
    
    # Fetch all settlements involving the user
    settlements = await crud_settlement.get_settlements_involving_user(db, user_id=user_id, limit=200) # Using a generous limit

    # Combine and sort the activities
    # We use a lambda to get the primary date for sorting from either type of object
    combined_activity = sorted(
        expenses + settlements, 
        key=lambda x: x.expense_date if isinstance(x, ExpenseModel) else x.settlement_date,
        reverse=True
    )

    return combined_activity 