from datetime import date
from decimal import Decimal
from django.core.exceptions import ValidationError
from django.db import transaction
from django.utils import timezone

from apps.accounting.models import Voucher
from apps.banking.models import BankAccount, ChequeLeaf
from apps.treasury.cheques.audit import log_cheque_audit
from apps.treasury.cheques.gl_helpers import (
    get_cheques_in_clearing_account,
    get_cheques_in_hand_account,
    get_treasury_settings,
    post_cheque_voucher,
)
from apps.treasury.cheques.models import (
    ChequeClearingEvent,
    ChequeDepositBatch,
    ChequeDepositLine,
    ReceivedCheque,
)
from apps.treasury.models import TreasurySettings


def _next_batch_no(company) -> str:
    count = ChequeDepositBatch.objects.filter(company=company).count() + 1
    return f"DEP-{timezone.localdate().strftime('%Y%m')}-{count:04d}"


class ChequeDepositService:
    @staticmethod
    @transaction.atomic
    def post_deposit_step1(
        *,
        leaf: ChequeLeaf,
        deposit_line: ChequeDepositLine | None,
        deposit_bank_account: BankAccount,
        deposit_date: date,
        deposit_slip_no: str,
        user,
    ) -> Voucher | None:
        """
        Clearing Step 1 (Deposit / Presentation):
        Dr Cheques-in-Clearing (1036)
        Cr Cheques-in-Hand (1035)
        Never credits Bank GL yet so bank balances are never overstated prior to clearing!
        """
        settings_obj = get_treasury_settings(leaf.company)
        step1_voucher = None
        if (
            settings_obj.cheque_accounting_mode == TreasurySettings.ChequeAccountingMode.CHEQUES_IN_HAND
            and leaf.amount > 0
            and not (deposit_line and deposit_line.clearing_step1_voucher_id)
        ):
            cih_acc = get_cheques_in_hand_account(leaf.company)
            cic_acc = get_cheques_in_clearing_account(leaf.company)
            step1_voucher = post_cheque_voucher(
                company=leaf.company,
                user=user,
                vtype=Voucher.VoucherType.CONTRA,
                vdate=deposit_date,
                project=leaf.project,
                reference_no=deposit_slip_no or leaf.cheque_number,
                currency=leaf.currency,
                narration=(
                    f"Deposit Step 1: Cheque #{leaf.cheque_number} transferred to Cheques-in-Clearing "
                    f"({deposit_bank_account.account_name}, Slip: {deposit_slip_no or 'N/A'})"
                ),
                lines_data=[
                    {
                        "account": cic_acc,
                        "debit": leaf.amount,
                        "credit": Decimal("0.00"),
                        "project": leaf.project,
                        "description": f"Cheque #{leaf.cheque_number} presented for clearing",
                    },
                    {
                        "account": cih_acc,
                        "debit": Decimal("0.00"),
                        "credit": leaf.amount,
                        "project": leaf.project,
                        "description": f"Remove #{leaf.cheque_number} from Cheques-in-Hand on deposit",
                    },
                ],
            )
            if deposit_line:
                deposit_line.clearing_step1_voucher = step1_voucher
                deposit_line.save(update_fields=["clearing_step1_voucher"])

        prev_status = leaf.status
        leaf.bank_account = deposit_bank_account
        leaf.deposit_date = deposit_date
        leaf.status = ChequeLeaf.Status.UNDER_CLEARING
        leaf.save(update_fields=["bank_account", "deposit_date", "status", "updated_at"])

        if hasattr(leaf, "received_profile"):
            prof = leaf.received_profile
            prof.deposit_bank_account = deposit_bank_account
            prof.deposit_slip_no = deposit_slip_no or prof.deposit_slip_no
            prof.workflow_status = ReceivedCheque.WorkflowStatus.UNDER_CLEARING
            prof.save(update_fields=["deposit_bank_account", "deposit_slip_no", "workflow_status", "updated_at"])

        ChequeClearingEvent.objects.create(
            company=leaf.company,
            cheque_leaf=leaf,
            deposit_line=deposit_line,
            event_type=ChequeClearingEvent.EventType.UNDER_CLEARING,
            event_date=deposit_date,
            from_status=prev_status,
            to_status=ChequeLeaf.Status.UNDER_CLEARING,
            voucher=step1_voucher,
            bank_reference=deposit_slip_no,
            actor=user,
            notes=f"Step 1 Deposited to {deposit_bank_account.account_name} (Slip {deposit_slip_no})",
        )
        log_cheque_audit(
            company=leaf.company,
            action="CHEQUE_DEPOSITED_STEP1",
            actor=user,
            cheque_leaf=leaf,
            previous_state={"status": prev_status},
            new_state={
                "status": ChequeLeaf.Status.UNDER_CLEARING,
                "deposit_slip_no": deposit_slip_no,
                "step1_voucher_no": step1_voucher.voucher_no if step1_voucher else "",
            },
        )
        return step1_voucher

    @staticmethod
    @transaction.atomic
    def create_deposit_batch(
        *,
        company,
        deposit_bank_account: BankAccount,
        cheque_ids: list,
        user,
        deposit_slip_no: str,
        deposit_date: date | None = None,
        bank_branch_name: str = "",
        notes: str = "",
    ) -> ChequeDepositBatch:
        if deposit_bank_account.company_id != company.id:
            raise ValidationError("Deposit bank account does not belong to this company.")
        if not cheque_ids:
            raise ValidationError("Select at least one received cheque for deposit.")

        dep_date = deposit_date or timezone.localdate()
        leaves = list(
            ChequeLeaf.objects.select_for_update().filter(
                company=company,
                id__in=cheque_ids,
                direction=ChequeLeaf.Direction.RECEIVED,
            )
        )
        if len(leaves) != len(set(str(i) for i in cheque_ids)):
            raise ValidationError("One or more selected cheques were not found in Received Cheque Register.")

        for lf in leaves:
            if lf.status not in (
                ChequeLeaf.Status.IN_HAND,
                ChequeLeaf.Status.RECEIVED,
                ChequeLeaf.Status.VERIFIED,
            ):
                raise ValidationError(
                    f"Cheque #{lf.cheque_number} is {lf.status} and cannot be added to a deposit batch."
                )

        total_amt = sum((lf.amount for lf in leaves), Decimal("0.00"))
        branch_lbl = bank_branch_name or (
            deposit_bank_account.bank_branch.name if deposit_bank_account.bank_branch else ""
        )
        batch = ChequeDepositBatch.objects.create(
            company=company,
            batch_no=_next_batch_no(company),
            deposit_bank_account=deposit_bank_account,
            bank_branch_name=branch_lbl,
            deposit_slip_no=deposit_slip_no.strip() or f"SLIP-{dep_date.strftime('%Y%m%d')}",
            deposit_date=dep_date,
            total_amount=total_amt,
            cheque_count=len(leaves),
            status=ChequeDepositBatch.Status.DEPOSITED,
            prepared_by=user,
            verified_by=user,
            verified_at=timezone.now(),
            notes=notes,
        )

        for lf in leaves:
            line = ChequeDepositLine.objects.create(
                batch=batch,
                cheque_leaf=lf,
                received_cheque=getattr(lf, "received_profile", None),
                amount=lf.amount,
                status=ChequeDepositLine.LineStatus.UNDER_CLEARING,
            )
            ChequeDepositService.post_deposit_step1(
                leaf=lf,
                deposit_line=line,
                deposit_bank_account=deposit_bank_account,
                deposit_date=dep_date,
                deposit_slip_no=batch.deposit_slip_no,
                user=user,
            )

        return batch

    @staticmethod
    def recompute_batch_status(batch: ChequeDepositBatch | None):
        if not batch:
            return
        lines = list(batch.lines.all())
        if not lines:
            return
        statuses = {ln.status for ln in lines}
        if statuses == {ChequeDepositLine.LineStatus.CLEARED}:
            batch.status = ChequeDepositBatch.Status.CLEARED
        elif ChequeDepositLine.LineStatus.BOUNCED in statuses and statuses != {ChequeDepositLine.LineStatus.BOUNCED}:
            batch.status = ChequeDepositBatch.Status.PARTIAL_BOUNCED
        elif ChequeDepositLine.LineStatus.CLEARED in statuses:
            batch.status = ChequeDepositBatch.Status.PARTIAL_CLEARED
        elif statuses == {ChequeDepositLine.LineStatus.BOUNCED}:
            batch.status = ChequeDepositBatch.Status.CLOSED
        else:
            batch.status = ChequeDepositBatch.Status.DEPOSITED
        batch.save(update_fields=["status", "updated_at"])

