from .models import SavingAccount
from ledgers.models import SystemTransactions
from django.db.models import Sum, F, Q
from loans.models import LoanApplicationWithHold
from .models import SavingsBlockedAmount,GroupSavingTransaction,SavingsProductInterestPayment
from django.utils import timezone
from django.utils.timezone import make_aware
from datetime import datetime,timedelta
import pytz

def get_account_balance(account, as_at=None):
    if not isinstance(account, SavingAccount):
        account = SavingAccount.objects.get(pk=account)

    mimimum_balance = account.account_product.min_balance
    blocked_amount = 0
    total_deposits = 0

    # Credits (Deposits)
    if as_at:
        account_credits = SystemTransactions.objects.filter(
            credit_chart=account.account_product.accounts_chart,
            record_date__date__lte=as_at,
            system_transactions__customer_account=account,
            system_transactions__deleted=False
        ).aggregate(total=Sum('amount'))['total']
    else:
        account_credits = SystemTransactions.objects.filter(
            credit_chart=account.account_product.accounts_chart,
            system_transactions__customer_account=account,
            system_transactions__deleted=False
        ).aggregate(total=Sum('amount'))['total']

    if account_credits:
        total_deposits = account_credits

    # Debits (Withdrawals)
    total_withdrawals = 0
    if as_at:
        debits = SystemTransactions.objects.filter(
            debit_chart=account.account_product.accounts_chart,
            record_date__date__lte=as_at,
            system_transactions__customer_account=account,
            system_transactions__deleted=False
        ).aggregate(total=Sum('amount'))['total']
    else:
        debits = SystemTransactions.objects.filter(
            debit_chart=account.account_product.accounts_chart,
            system_transactions__customer_account=account,
            system_transactions__deleted=False
        ).aggregate(total=Sum('amount'))['total']

    if debits:
        total_withdrawals = debits

    # Withheld Amounts
    if as_at:
        with_held_totals = LoanApplicationWithHold.objects.filter(
            account=account,  # only this savings account
            status='held',
            hold_type='savings',
            date_added__date__lte=as_at
        ).aggregate(total_held_savings=Sum('amount'))
    else:
        with_held_totals = LoanApplicationWithHold.objects.filter(
            account=account,  # only this savings account
            status='held',
            hold_type='savings'
        ).aggregate(total_held_savings=Sum('amount'))

    total_held_amount = (
        with_held_totals['total_held_savings']
        if with_held_totals['total_held_savings'] else 0
    )

    # Blocked Amounts 
    if as_at:
        blocked_totals = SavingsBlockedAmount.objects.filter(
            customer_account=account,
            status='active',
            date_added__date__lte=as_at
        ).aggregate(total_blocked_savings=Sum('amount'))
    else:
        blocked_totals = SavingsBlockedAmount.objects.filter(
            customer_account=account,
            status='active'
        ).aggregate(total_blocked_savings=Sum('amount'))

    blocked_amount = (
        blocked_totals['total_blocked_savings']
        if blocked_totals['total_blocked_savings'] else 0
    )

    return {
        'total_deposits': total_deposits,
        'total_withdrawals': total_withdrawals,
        'balance': f"{total_deposits - (total_withdrawals + mimimum_balance + blocked_amount + total_held_amount):,}",
        'balance_raw': total_deposits - (total_withdrawals + mimimum_balance + blocked_amount + total_held_amount),
        'balance_actual': total_deposits - total_withdrawals,
        "with_held": total_held_amount,
        # amazonq-ignore-next-line
        "blocked_amount": blocked_amount
    }


def get_group_memebr_account_balance(account,customer):
    balance = 0
    if customer and account:
        # amazonq-ignore-next-line
        chart = account.account_product.accounts_chart.id
        filter_array = {"savings__customer_account":account,"membership__member":customer,"savings__transaction__transaction_type":"normal"}
        group_savings = GroupSavingTransaction.objects.filter(**filter_array)
        if group_savings:
            for group_saving in group_savings:
                if chart == group_saving.savings.transaction.credit_chart.id:
                    balance += group_saving.savings.transaction.amount
                else:
                    balance -= group_saving.savings.transaction.amount
    return balance
