"""
IntegrationService - Automatic journal entry creation for loan and expense transactions.

Account codes used (canonical Grazuri Haven accounts):
  1010  Cash and Bank Balances       (asset)
  1011  Cash on Hand                 (asset)
  1012  Bank Account – Main Operating (asset)
  1013  M-Pesa / SasaPay Float       (asset)
  1020  Loan Portfolio – Performing  (asset)
  4010  Interest Income – Loans      (income)
  4020  Fee Income – Processing Fees (income)
  401002 Fee Income                  (income)
  501001 Operating Expenses          (expense)
  501002 Staff Salaries              (expense)

Reference-number prefixes (must stay in sync with signals.py):
  DISB-{loan_number}           loan disbursement
  FEE-{loan_number}            processing-fee income
  REP-{receipt_number}         repayment received
  INT-{loan_number}            interest recognition (on final repayment)
  EXP-{expense_id}             expense
"""

from decimal import Decimal
from typing import Optional

from django.contrib.auth import get_user_model
from django.db import transaction
from django.utils import timezone

from accounting.models import Account, JournalEntry, JournalEntryLine
from accounting.services.accounting_service import AccountingService

User = get_user_model()

# ---------------------------------------------------------------------------
# Account-code constants — all accounts must exist in the DB before entries
# can be posted.  These codes are the stable "real" Chart-of-Accounts codes
# that were created by the backfill migration.
# ---------------------------------------------------------------------------
CODE_CASH_AND_BANK = '1010'      # fallback / generic cash
CODE_CASH_ON_HAND  = '1011'
CODE_BANK_MAIN     = '1012'
CODE_MPESA         = '1013'
CODE_LOAN_PORTFOLIO = '1020'
CODE_INTEREST_INCOME = '4010'
CODE_FEE_INCOME      = '4020'
CODE_FEE_INCOME_ALT  = '401002'  # kept for backward compat in older entries

# Expense account mapping  category → account code
EXPENSE_ACCOUNT_MAP = {
    'operational':  '501001',
    'staff':        '501002',
    'marketing':    '501001',
    'loan_related': '501001',
    'utilities':    '501001',
    'office':       '501001',
    'transport':    '501001',
    'maintenance':  '501001',
    'other':        '501001',
}

# Payment-method → cash account code
PAYMENT_ACCOUNT_MAP = {
    'cash':   CODE_CASH_ON_HAND,
    'mpesa':  CODE_MPESA,
    'bank':   CODE_BANK_MAIN,
    'cheque': CODE_BANK_MAIN,
}


class IntegrationService:
    """
    Creates double-entry journal entries from loan and expense transactions.

    All entries are automatically posted (status='posted') inside atomic
    transactions.  If the accounting_service raises a ValidationError the
    caller receives it so upper layers can handle it explicitly.
    """

    def __init__(self):
        self.accounting_service = AccountingService()
        self._account_cache: dict = {}

    # ------------------------------------------------------------------
    # Internal helpers
    # ------------------------------------------------------------------

    def _get_account(self, code: str) -> Account:
        """Return an active Account by code, using a per-instance cache."""
        if code not in self._account_cache:
            self._account_cache[code] = Account.objects.get(code=code, is_active=True)
        return self._account_cache[code]

    def _cash_account_for_repayment(self, repayment) -> Account:
        """
        Pick the correct cash/bank account based on payment method / source.

        Falls back gracefully to the generic Cash and Bank Balances account
        if the specific account doesn't exist yet.
        """
        # M-Pesa payments → M-Pesa Float account
        if getattr(repayment, 'payment_method', '') == 'mpesa' or \
                getattr(repayment, 'payment_source', '') == 'automatic':
            try:
                return self._get_account(CODE_MPESA)
            except Account.DoesNotExist:
                pass

        method = getattr(repayment, 'payment_method', 'cash')
        code = PAYMENT_ACCOUNT_MAP.get(method, CODE_CASH_AND_BANK)
        try:
            return self._get_account(code)
        except Account.DoesNotExist:
            return self._get_account(CODE_CASH_AND_BANK)

    def _cash_account_for_expense(self, payment_method: str) -> Account:
        """Pick the cash/bank account for an expense payment method."""
        code = PAYMENT_ACCOUNT_MAP.get(payment_method, CODE_CASH_AND_BANK)
        try:
            return self._get_account(code)
        except Account.DoesNotExist:
            return self._get_account(CODE_CASH_AND_BANK)

    def _resolve_user(self, *candidates):
        """Return the first non-None user from the list, or None."""
        for candidate in candidates:
            if candidate is not None:
                return candidate
        return None

    # ------------------------------------------------------------------
    # Public API
    # ------------------------------------------------------------------

    @transaction.atomic
    def create_loan_disbursement_entry(self, loan, user=None) -> JournalEntry:
        """
        Post the journal entry for a loan disbursement.

        Entry:
            DR  Loan Portfolio – Performing  (1020)   principal_amount
            CR  Cash and Bank Balances       (1010)   principal_amount

        Returns the posted JournalEntry.
        """
        user = self._resolve_user(
            user,
            getattr(loan, 'approved_by', None),
            getattr(loan, 'disbursed_by', None),
            getattr(loan, 'loan_officer', None),
        )

        loan_portfolio_account = self._get_account(CODE_LOAN_PORTFOLIO)
        cash_account = self._get_account(CODE_CASH_AND_BANK)

        tx_date = loan.disbursement_date
        if hasattr(tx_date, 'date'):
            tx_date = tx_date.date()
        if tx_date is None:
            tx_date = timezone.now().date()

        journal_entry = JournalEntry.objects.create(
            reference_number=f'DISB-{loan.loan_number}',
            transaction_date=tx_date,
            description=(
                f'Loan Disbursement – {loan.borrower.get_full_name()} '
                f'({loan.loan_number})'
            ),
            status='draft',
            branch=getattr(loan, 'branch', None) or getattr(loan.borrower, 'branch', None),
            loan=loan,
            created_by=user,
        )

        JournalEntryLine.objects.create(
            journal_entry=journal_entry,
            account=loan_portfolio_account,
            description=f'Loan disbursed to {loan.borrower.get_full_name()}',
            debit_amount=loan.principal_amount,
            credit_amount=Decimal('0.00'),
            line_number=1,
        )
        JournalEntryLine.objects.create(
            journal_entry=journal_entry,
            account=cash_account,
            description=f'Disbursement payment – {loan.loan_number}',
            debit_amount=Decimal('0.00'),
            credit_amount=loan.principal_amount,
            line_number=2,
        )

        self.accounting_service.post_journal_entry(journal_entry, user)
        return journal_entry

    @transaction.atomic
    def create_loan_repayment_entry(self, repayment, user=None) -> JournalEntry:
        """
        Post the journal entry for a loan repayment.

        For this business model the company pre-deducts interest before
        disbursement (total_amount == principal_amount).  Repayments
        therefore reduce the loan portfolio balance only — there is no
        separate interest line on each repayment.

        Entry:
            DR  Cash / M-Pesa Account         amount
            CR  Loan Portfolio – Performing   amount

        Interest recognition is handled separately by
        create_interest_recognition_entry() which is called when the loan
        status changes to 'paid'.

        Returns the posted JournalEntry.
        """
        loan = repayment.loan
        user = self._resolve_user(
            user,
            # Repayment does not have recorded_by — fall back to loan staff
            getattr(loan, 'loan_officer', None),
            getattr(loan, 'approved_by', None),
        )

        cash_account = self._cash_account_for_repayment(repayment)
        loan_portfolio_account = self._get_account(CODE_LOAN_PORTFOLIO)

        tx_date = repayment.payment_date
        if hasattr(tx_date, 'date'):
            tx_date = tx_date.date()

        journal_entry = JournalEntry.objects.create(
            reference_number=f'REP-{repayment.receipt_number}',
            transaction_date=tx_date,
            description=(
                f'Loan Repayment – {loan.borrower.get_full_name()} '
                f'({loan.loan_number})'
            ),
            status='draft',
            branch=(
                getattr(loan, 'branch', None)
                or getattr(loan.borrower, 'branch', None)
            ),
            loan=loan,
            created_by=user,
        )

        # DR: Cash received
        JournalEntryLine.objects.create(
            journal_entry=journal_entry,
            account=cash_account,
            description=f'Payment received – {repayment.payment_method}',
            debit_amount=repayment.amount,
            credit_amount=Decimal('0.00'),
            line_number=1,
        )
        # CR: Reduce Loan Portfolio
        JournalEntryLine.objects.create(
            journal_entry=journal_entry,
            account=loan_portfolio_account,
            description=f'Repayment received – {loan.loan_number}',
            debit_amount=Decimal('0.00'),
            credit_amount=repayment.amount,
            line_number=2,
        )

        self.accounting_service.post_journal_entry(journal_entry, user)
        return journal_entry

    @transaction.atomic
    def create_interest_recognition_entry(self, loan, user=None) -> Optional[JournalEntry]:
        """
        Recognise interest income when a loan is fully repaid.

        Because this business pre-deducts interest before disbursement,
        interest is recognised as income only once the loan is closed.

        Entry:
            DR  Cash and Bank Balances       interest_amount
            CR  Interest Income – Loans      interest_amount

        Returns None if there is no interest to recognise.
        """
        interest_amount = getattr(loan, 'interest_amount', Decimal('0.00')) or Decimal('0.00')
        if interest_amount <= Decimal('0.00'):
            return None

        # Check if already posted
        from accounting.models import JournalEntry as JE
        if JE.objects.filter(reference_number=f'INT-{loan.loan_number}').exists():
            return None

        user = self._resolve_user(
            user,
            getattr(loan, 'loan_officer', None),
            getattr(loan, 'approved_by', None),
        )

        cash_account = self._get_account(CODE_CASH_AND_BANK)
        interest_income_account = self._get_account(CODE_INTEREST_INCOME)

        tx_date = timezone.now().date()

        journal_entry = JournalEntry.objects.create(
            reference_number=f'INT-{loan.loan_number}',
            transaction_date=tx_date,
            description=(
                f'Interest Income – {loan.borrower.get_full_name()} '
                f'({loan.loan_number})'
            ),
            status='draft',
            branch=(
                getattr(loan, 'branch', None)
                or getattr(loan.borrower, 'branch', None)
            ),
            loan=loan,
            created_by=user,
        )

        JournalEntryLine.objects.create(
            journal_entry=journal_entry,
            account=cash_account,
            description=f'Interest income – {loan.loan_number}',
            debit_amount=interest_amount,
            credit_amount=Decimal('0.00'),
            line_number=1,
        )
        JournalEntryLine.objects.create(
            journal_entry=journal_entry,
            account=interest_income_account,
            description=f'Interest income – {loan.loan_number}',
            debit_amount=Decimal('0.00'),
            credit_amount=interest_amount,
            line_number=2,
        )

        self.accounting_service.post_journal_entry(journal_entry, user)
        return journal_entry

    @transaction.atomic
    def create_processing_fee_entry(self, loan, user=None) -> Optional[JournalEntry]:
        """
        Post a journal entry for the processing fee when it is greater than zero.

        Entry:
            DR  Cash and Bank Balances     processing_fee
            CR  Fee Income                 processing_fee

        Returns None if no fee exists.
        """
        fee = getattr(loan, 'processing_fee', Decimal('0.00')) or Decimal('0.00')
        if fee <= Decimal('0.00'):
            return None

        # Idempotency guard
        from accounting.models import JournalEntry as JE
        if JE.objects.filter(reference_number=f'FEE-{loan.loan_number}').exists():
            return None

        user = self._resolve_user(
            user,
            getattr(loan, 'approved_by', None),
            getattr(loan, 'loan_officer', None),
        )

        cash_account = self._get_account(CODE_CASH_AND_BANK)
        fee_income_account = self._get_account(CODE_FEE_INCOME)

        tx_date = loan.disbursement_date
        if hasattr(tx_date, 'date'):
            tx_date = tx_date.date()
        if tx_date is None:
            tx_date = timezone.now().date()

        journal_entry = JournalEntry.objects.create(
            reference_number=f'FEE-{loan.loan_number}',
            transaction_date=tx_date,
            description=(
                f'Processing Fee – {loan.borrower.get_full_name()} '
                f'({loan.loan_number})'
            ),
            status='draft',
            branch=(
                getattr(loan, 'branch', None)
                or getattr(loan.borrower, 'branch', None)
            ),
            loan=loan,
            created_by=user,
        )

        JournalEntryLine.objects.create(
            journal_entry=journal_entry,
            account=cash_account,
            description=f'Processing fee collected – {loan.loan_number}',
            debit_amount=fee,
            credit_amount=Decimal('0.00'),
            line_number=1,
        )
        JournalEntryLine.objects.create(
            journal_entry=journal_entry,
            account=fee_income_account,
            description=f'Processing fee income – {loan.loan_number}',
            debit_amount=Decimal('0.00'),
            credit_amount=fee,
            line_number=2,
        )

        self.accounting_service.post_journal_entry(journal_entry, user)
        return journal_entry

    @transaction.atomic
    def create_expense_entry(self, expense, user=None) -> JournalEntry:
        """
        Post a journal entry for an approved expense.

        Entry:
            DR  Expense Account    expense.amount
            CR  Payment Account    expense.amount

        Returns the posted JournalEntry.
        """
        user = self._resolve_user(
            user,
            getattr(expense, 'approved_by', None),
        )

        expense_account_code = EXPENSE_ACCOUNT_MAP.get(
            getattr(expense, 'category', 'other'), '501001'
        )
        expense_account = self._get_account(expense_account_code)
        payment_account = self._cash_account_for_expense(
            getattr(expense, 'payment_method', 'cash')
        )

        tx_date = expense.expense_date
        if hasattr(tx_date, 'date'):
            tx_date = tx_date.date()
        if tx_date is None:
            tx_date = timezone.now().date()

        journal_entry = JournalEntry.objects.create(
            reference_number=f'EXP-{expense.id}',
            transaction_date=tx_date,
            description=f'Expense – {getattr(expense, "category", "other")} – {str(expense.description)[:100]}',
            status='draft',
            branch=getattr(expense, 'branch', None),
            expense=expense,
            created_by=user,
        )

        JournalEntryLine.objects.create(
            journal_entry=journal_entry,
            account=expense_account,
            description=str(expense.description)[:200],
            debit_amount=expense.amount,
            credit_amount=Decimal('0.00'),
            line_number=1,
        )
        JournalEntryLine.objects.create(
            journal_entry=journal_entry,
            account=payment_account,
            description=f'Payment via {getattr(expense, "payment_method", "cash")}',
            debit_amount=Decimal('0.00'),
            credit_amount=expense.amount,
            line_number=2,
        )

        self.accounting_service.post_journal_entry(journal_entry, user)
        return journal_entry

    # ------------------------------------------------------------------
    # Legacy / compatibility shims
    # ------------------------------------------------------------------

    @transaction.atomic
    def create_interest_accrual_entry(
        self, loan, interest_amount: Decimal, accrual_date, user: User
    ) -> JournalEntry:
        """
        Accrual-basis interest entry (kept for backward compatibility).

        Entry:
            DR  Cash and Bank Balances (1010)     interest_amount
            CR  Interest Income – Loans (4010)    interest_amount
        """
        cash_account = self._get_account(CODE_CASH_AND_BANK)
        interest_income_account = self._get_account(CODE_INTEREST_INCOME)

        if hasattr(accrual_date, 'date'):
            accrual_date = accrual_date.date()

        ref = f'INT-ACCR-{loan.loan_number}-{accrual_date}'

        journal_entry = JournalEntry.objects.create(
            reference_number=ref,
            transaction_date=accrual_date,
            description=(
                f'Interest Accrual – {loan.borrower.get_full_name()} '
                f'({loan.loan_number})'
            ),
            status='draft',
            branch=(
                getattr(loan, 'branch', None)
                or getattr(loan.borrower, 'branch', None)
            ),
            loan=loan,
            created_by=user,
        )

        JournalEntryLine.objects.create(
            journal_entry=journal_entry,
            account=cash_account,
            description=f'Interest accrued – {loan.loan_number}',
            debit_amount=interest_amount,
            credit_amount=Decimal('0.00'),
            line_number=1,
        )
        JournalEntryLine.objects.create(
            journal_entry=journal_entry,
            account=interest_income_account,
            description=f'Interest income recognition – {loan.loan_number}',
            debit_amount=Decimal('0.00'),
            credit_amount=interest_amount,
            line_number=2,
        )

        self.accounting_service.post_journal_entry(journal_entry, user)
        return journal_entry
