"""
Financial Reports Service
Provides data for:
  1. SasaPay Reconciliation (Money In / Money Out / Control Account)
  2. Profit & Loss Statement (integrated with Chart of Accounts)
  3. Financial Statements (Balance Sheet style with GL integration)
  4. Loan Aging Report
"""

from decimal import Decimal
from datetime import date, timedelta
from django.db.models import Sum, Count, Q
from django.utils import timezone
from django.core.cache import cache

# Module-level imports used by get_profit_and_loss and get_financial_statements
# (kept here so unit tests can patch them at the module level)
from accounting.models import Account
from accounting.services.accounting_service import AccountingService
from accounting.services.report_service import ReportService


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

def _d(value):
    """Coerce value to Decimal, defaulting to 0."""
    if value is None:
        return Decimal('0.00')
    return Decimal(str(value)).quantize(Decimal('0.01'))


def _date_range_filter(start_date=None, end_date=None):
    """Return a dict suitable for ** unpacking into a queryset filter."""
    f = {}
    if start_date:
        f['__gte'] = start_date
    if end_date:
        f['__lte'] = end_date
    return f


# ---------------------------------------------------------------------------
# 1. SasaPay Reconciliation
# ---------------------------------------------------------------------------

def get_sasapay_reconciliation(start_date=None, end_date=None):
    """
    Returns a reconciliation dict with:
      - money_in:  all processed IPN payments (C2B repayments via SasaPay)
      - money_out: all successful B2C disbursements via SasaPay
      - ipn_logs:  breakdown by processing_status
      - unknown_payments: unmatched payments
      - stk_results: STK push results
      - control_account: running balance summary
    """
    from payments.sasapay_models import (
        SasaPayIPNLog, SasaPayDisbursementResult, SasaPayUnknownPayment,
        SasaPaySTKResult
    )
    from loans.models import Repayment

    # ------ Money IN (C2B repayments linked to SasaPay IPN) ------
    repayments_qs = Repayment.objects.filter(payment_source='automatic')
    if start_date:
        repayments_qs = repayments_qs.filter(payment_date__date__gte=start_date)
    if end_date:
        repayments_qs = repayments_qs.filter(payment_date__date__lte=end_date)

    money_in_total = _d(repayments_qs.aggregate(t=Sum('amount'))['t'])
    money_in_count = repayments_qs.count()

    # Also aggregate from IPN logs (processed only) as cross-check
    ipn_qs = SasaPayIPNLog.objects.all()
    if start_date:
        ipn_qs = ipn_qs.filter(created_at__date__gte=start_date)
    if end_date:
        ipn_qs = ipn_qs.filter(created_at__date__lte=end_date)

    ipn_by_status = {}
    for row in ipn_qs.values('processing_status').annotate(cnt=Count('id')):
        ipn_by_status[row['processing_status']] = row['cnt']

    ipn_total = ipn_qs.count()
    ipn_processed = ipn_by_status.get('processed', 0)
    ipn_no_match = ipn_by_status.get('no_match', 0)
    ipn_duplicate = ipn_by_status.get('duplicate', 0)
    ipn_failed = ipn_by_status.get('failed', 0)
    ipn_pending = ipn_by_status.get('pending', 0)

    # ------ Money OUT (B2C disbursements) ------
    disb_qs = SasaPayDisbursementResult.objects.all()
    if start_date:
        disb_qs = disb_qs.filter(created_at__date__gte=start_date)
    if end_date:
        disb_qs = disb_qs.filter(created_at__date__lte=end_date)

    disb_success_qs = disb_qs.filter(result_code='0')
    money_out_total = _d(disb_success_qs.aggregate(t=Sum('trans_amount'))['t'])
    money_out_count = disb_success_qs.count()
    money_out_failed = disb_qs.exclude(result_code='0').count()

    last_merchant_balance = _d(
        disb_success_qs.order_by('-created_at').values_list('merchant_balance', flat=True).first()
    )

    # ------ Unknown / Unmatched payments ------
    unknown_qs = SasaPayUnknownPayment.objects.all()
    if start_date:
        unknown_qs = unknown_qs.filter(created_at__date__gte=start_date)
    if end_date:
        unknown_qs = unknown_qs.filter(created_at__date__lte=end_date)

    unknown_total = _d(unknown_qs.aggregate(t=Sum('amount'))['t'])
    unknown_count = unknown_qs.count()
    unknown_unresolved = unknown_qs.filter(resolved=False).count()

    # ------ STK Push results ------
    stk_qs = SasaPaySTKResult.objects.all()
    if start_date:
        stk_qs = stk_qs.filter(created_at__date__gte=start_date)
    if end_date:
        stk_qs = stk_qs.filter(created_at__date__lte=end_date)

    stk_success = stk_qs.filter(result_code='0')
    stk_in_total = _d(stk_success.aggregate(t=Sum('trans_amount'))['t'])
    stk_in_count = stk_success.count()
    stk_failed_count = stk_qs.exclude(result_code='0').count()

    # ------ Control Account Balance ------
    # Opening = money that came in (repayments) - money that went out (disbursements)
    net_position = money_in_total + stk_in_total - money_out_total

    return {
        'period': {'start': start_date, 'end': end_date},
        'money_in': {
            'repayments_total': money_in_total,
            'repayments_count': money_in_count,
            'stk_total': stk_in_total,
            'stk_count': stk_in_count,
            'grand_total': money_in_total + stk_in_total,
        },
        'money_out': {
            'disbursements_total': money_out_total,
            'disbursements_count': money_out_count,
            'disbursements_failed': money_out_failed,
        },
        'control_account': {
            'net_position': net_position,
            'last_merchant_balance': last_merchant_balance,
        },
        'ipn_summary': {
            'total': ipn_total,
            'processed': ipn_processed,
            'no_match': ipn_no_match,
            'duplicate': ipn_duplicate,
            'failed': ipn_failed,
            'pending': ipn_pending,
        },
        'unknown_payments': {
            'total_amount': unknown_total,
            'count': unknown_count,
            'unresolved': unknown_unresolved,
        },
        'stk_summary': {
            'success_count': stk_in_count,
            'failed_count': stk_failed_count,
        },
        'ipn_detail_qs': ipn_qs.order_by('-created_at'),
        'disbursement_detail_qs': disb_qs.order_by('-created_at'),
        'unknown_detail_qs': unknown_qs.order_by('-created_at'),
    }


# ---------------------------------------------------------------------------
# 2. Profit & Loss Statement (integrated with Chart of Accounts)
# ---------------------------------------------------------------------------

def get_profit_and_loss(start_date=None, end_date=None, branch_id=None):
    """
    Returns a P&L dict sourced exclusively from the accounting General Ledger via
    ReportService.  No fallback to Loan/Expense model queries for income or expense
    figures.

    INCOME / EXPENSES — from GL via ReportService.generate_income_statement
    CASH FLOW SUPPLEMENTARY — loan disbursements and repayments collected (informational
        only; not counted as income)

    Requirements: 2.1, 2.3
    """
    from loans.models import Loan, Repayment

    report_service = ReportService()

    if start_date and end_date:
        result = report_service.generate_income_statement(
            start_date=start_date,
            end_date=end_date,
            branch=None,  # branch_id → Branch mapping handled at call site if needed
        )
    else:
        result = {
            'period': {'start': None, 'end': None},
            'income': {},
            'expenses': {},
            'totals': {
                'gross_income': Decimal('0.00'),
                'total_expenses': Decimal('0.00'),
                'net_income': Decimal('0.00'),
            },
        }

    result.setdefault('source', 'accounting_system')
    result.setdefault('generated_at', timezone.now().isoformat())

    # ------------------------------------------------------------------
    # Cash-flow supplementary block (informational; not income)
    # Uses Loan/Repayment queries solely for cash movement context.
    # ------------------------------------------------------------------
    loan_qs = Loan.objects.filter(is_deleted=False)
    if branch_id:
        loan_qs = loan_qs.filter(borrower__branch_id=branch_id)
    if start_date:
        loan_qs = loan_qs.filter(disbursement_date__date__gte=start_date)
    if end_date:
        loan_qs = loan_qs.filter(disbursement_date__date__lte=end_date)

    loans_disbursed = _d(loan_qs.aggregate(principal=Sum('principal_amount'))['principal'])
    total_loans_count = loan_qs.count()

    rep_qs = Repayment.objects.all()
    if start_date:
        rep_qs = rep_qs.filter(payment_date__date__gte=start_date)
    if end_date:
        rep_qs = rep_qs.filter(payment_date__date__lte=end_date)
    if branch_id:
        rep_qs = rep_qs.filter(loan__borrower__branch_id=branch_id)
    total_repayments_collected = _d(rep_qs.aggregate(t=Sum('amount'))['t'])

    result['cash_flow_supplementary'] = {
        'loans_disbursed': loans_disbursed,
        'repayments_collected': total_repayments_collected,
        'net_cash': total_repayments_collected - loans_disbursed,
        'loan_count': total_loans_count,
    }

    return result


# ---------------------------------------------------------------------------
# 3. Financial Statements (Balance Sheet integrated with Chart of Accounts)
# ---------------------------------------------------------------------------

def get_financial_statements(as_of_date=None, branch_id=None):
    """
    Returns a financial statements dict (Statement of Financial Position / Balance Sheet)
    sourced exclusively from the General Ledger via AccountingService.calculate_account_balance.

    All asset, liability, and equity balances are derived from the Chart of Accounts.
    Each line item includes account_code and name from the Chart of Accounts.

    If no Account records exist, returns a zero-valued SFP dict with source: 'accounting_system'.

    Requirements: 4.1, 4.2, 4.3
    """
    import logging

    logger = logging.getLogger(__name__)
    as_of = as_of_date or date.today()
    accounting_service = AccountingService()

    # Zero-valued structure returned when no Chart of Accounts records exist (Req 4.2)
    _zero_sfp = {
        'as_of': as_of,
        'as_of_date': as_of,
        'source': 'accounting_system',
        'generated_at': timezone.now().isoformat(),
        'assets': {
            'items': [],
            'total_assets': Decimal('0.00'),
        },
        'liabilities': {
            'items': [],
            'total_liabilities': Decimal('0.00'),
        },
        'equity': {
            'items': [],
            'total_equity': Decimal('0.00'),
        },
        'balanced': True,
        'difference': Decimal('0.00'),
    }

    # Check if Chart of Accounts has any records at all (Req 4.2)
    if not Account.objects.filter(is_active=True).exists():
        return _zero_sfp

    # Resolve branch object from branch_id if provided
    branch = None
    if branch_id:
        try:
            from accounting.models import Branch
            branch = Branch.objects.get(id=branch_id)
        except Exception:
            pass

    def _build_line_items(account_type):
        """
        Return a list of line item dicts and a total for all active accounts of a given type.
        Each item contains: account_code, name, balance.
        Uses AccountingService.calculate_account_balance exclusively (Req 4.1, 4.3).
        """
        items = []
        total = Decimal('0.00')
        accounts = Account.objects.filter(account_type=account_type, is_active=True).order_by('code')
        for account in accounts:
            balance = _d(accounting_service.calculate_account_balance(
                account=account,
                as_of_date=as_of,
                branch=branch,
            ))
            items.append({
                'account_code': account.code,   # Req 4.3
                'name': account.name,            # Req 4.3
                'balance': balance,
                'subtype': account.subtype or '',
            })
            total += balance
        return items, total

    asset_items, total_assets = _build_line_items('asset')
    liability_items, total_liabilities = _build_line_items('liability')
    equity_items, total_equity = _build_line_items('equity')

    # Req 4.1 / 5.1: compute balance equation check
    difference = _d(abs(total_assets - (total_liabilities + total_equity)))
    balanced = difference < Decimal('0.01')
    if not balanced:
        logger.error(
            'SFP imbalance in get_financial_statements: assets=%s liabilities=%s equity=%s '
            'difference=%s as_of=%s',
            total_assets, total_liabilities, total_equity, difference, as_of,
        )

    return {
        'as_of': as_of,
        'as_of_date': as_of,
        'source': 'accounting_system',
        'generated_at': timezone.now().isoformat(),
        'assets': {
            'items': asset_items,
            'total_assets': total_assets,
        },
        'liabilities': {
            'items': liability_items,
            'total_liabilities': total_liabilities,
        },
        'equity': {
            'items': equity_items,
            'total_equity': total_equity,
        },
        'balanced': balanced,
        'difference': difference,
    }


def _get_account_balance(accounting_service, account_code, as_of_date, branch_id=None):
    """
    Helper to get account balance from accounting service.
    
    Returns Decimal balance or 0.00 if account not found.
    """
    try:
        from accounting.models import Account
        account = Account.objects.get(code=account_code, is_active=True)
        # calculate_account_balance returns a Decimal directly, not a dict
        balance = accounting_service.calculate_account_balance(
            account=account,
            as_of_date=as_of_date,
            branch=None  # TODO: Map branch_id to Branch object if needed
        )
        return _d(balance)
    except Exception as e:
        # Log the error for debugging
        import logging
        logger = logging.getLogger(__name__)
        logger.warning(f'Could not get balance for account {account_code}: {e}')
        return Decimal('0.00')


# ---------------------------------------------------------------------------
# 4. Loan Aging Report
# ---------------------------------------------------------------------------

AGING_BUCKETS = [
    ('Current (not overdue)', 0, 0),
    ('1 – 30 days', 1, 30),
    ('31 – 60 days', 31, 60),
    ('61 – 90 days', 61, 90),
    ('91 – 180 days', 91, 180),
    ('181 – 365 days', 181, 365),
    ('Over 365 days', 366, None),
]


def get_loan_aging(branch_id=None, product_id=None, include_detail=True):
    """
    Returns an aging report dict with buckets and optional per-loan detail.

    Each bucket has:
      - label, days_min, days_max
      - count, principal, outstanding, percentage_of_portfolio
    """
    from loans.models import Loan, Repayment

    today = date.today()

    active_qs = Loan.objects.filter(status='active', is_deleted=False)
    if branch_id:
        active_qs = active_qs.filter(borrower__branch_id=branch_id)
    if product_id:
        active_qs = active_qs.filter(application__loan_product_id=product_id)

    # Compute days past due for each loan in Python (avoids DB-level date math issues
    # across MySQL/SQLite; the queryset is normally small for active loans)
    loans_data = list(
        active_qs.select_related('borrower', 'application__loan_product')
        .values(
            'id', 'loan_number', 'principal_amount', 'total_amount', 'due_date',
            'borrower__first_name', 'borrower__last_name', 'borrower__phone_number',
            'application__loan_product__name',
            '_amount_paid_cache',
        )
    )

    # Fetch all repayment sums for these loans in one query
    loan_ids = [r['id'] for r in loans_data]
    paid_map = {}
    for row in (
        Repayment.objects.filter(loan_id__in=loan_ids)
        .values('loan_id')
        .annotate(paid=Sum('amount'))
    ):
        paid_map[row['loan_id']] = _d(row['paid'])

    total_portfolio = Decimal('0.00')
    augmented = []
    for r in loans_data:
        due = r['due_date']
        if hasattr(due, 'date'):
            due = due.date()
        days_past_due = max(0, (today - due).days) if due else 0
        # FIX: Use total_amount (includes interest) instead of principal_amount
        outstanding = _d(r['total_amount']) - paid_map.get(r['id'], Decimal('0.00'))
        outstanding = max(Decimal('0.00'), outstanding)
        total_portfolio += outstanding
        augmented.append({
            'id': r['id'],
            'loan_number': r['loan_number'],
            'borrower_name': f"{r['borrower__first_name']} {r['borrower__last_name']}".strip(),
            'borrower_phone': r['borrower__phone_number'],
            'product': r['application__loan_product__name'],
            'principal': _d(r['principal_amount']),
            'outstanding': outstanding,
            'due_date': due,
            'days_past_due': days_past_due,
        })

    # Build buckets
    buckets = []
    for label, dmin, dmax in AGING_BUCKETS:
        if dmin == 0 and dmax == 0:
            bucket_loans = [l for l in augmented if l['days_past_due'] == 0]
        elif dmax is None:
            bucket_loans = [l for l in augmented if l['days_past_due'] >= dmin]
        else:
            bucket_loans = [l for l in augmented if dmin <= l['days_past_due'] <= dmax]

        bucket_outstanding = sum((l['outstanding'] for l in bucket_loans), Decimal('0.00'))
        pct = (
            (bucket_outstanding / total_portfolio * 100)
            if total_portfolio else Decimal('0.00')
        )
        buckets.append({
            'label': label,
            'days_min': dmin,
            'days_max': dmax,
            'count': len(bucket_loans),
            'outstanding': bucket_outstanding,
            'percentage': round(float(pct), 1),
            'loans': bucket_loans if include_detail else [],
        })

    overdue_buckets = buckets[1:]  # exclude current
    total_overdue = sum((b['outstanding'] for b in overdue_buckets), Decimal('0.00'))
    overdue_count = sum(b['count'] for b in overdue_buckets)

    return {
        'as_of': today,
        'total_portfolio': total_portfolio,
        'total_active_loans': len(augmented),
        'total_overdue': total_overdue,
        'overdue_count': overdue_count,
        'par_ratio': round(float(total_overdue / total_portfolio * 100) if total_portfolio else 0, 2),
        'buckets': buckets,
        'all_loans': augmented,  # for export / detail view
    }
