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 Account, Party, Voucher
from apps.accounting.services import PostingService
from apps.banking.models import BankAccount, ChequeBook, ChequeLeaf, normalize_cheque_number
from apps.party_hub.services.sync import OpenItemSyncService
from apps.projects.models import Project
from apps.treasury.cheques.audit import log_cheque_audit
from apps.treasury.cheques.cheque_books.service import ChequeBookService
from apps.treasury.cheques.gl_helpers import (
    get_creditors_control_account,
    get_treasury_settings,
    post_cheque_voucher,
)
from apps.treasury.cheques.models import (
    ChequeApproval,
    ChequeCancellation,
    ChequeClearingEvent,
    IssuedCheque,
)
from apps.treasury.cheques.permissions import enforce_maker_checker


class IssuedChequeService:
    @staticmethod
    @transaction.atomic
    def issue_cheque(
        *,
        company,
        bank_account: BankAccount,
        user,
        payee_name: str,
        amount: Decimal,
        cheque_date: date | None = None,
        issue_date: date | None = None,
        expected_presentation_date: date | None = None,
        cheque_leaf: ChequeLeaf | None = None,
        cheque_book: ChequeBook | None = None,
        cheque_number: str = "",
        payee_type: str = IssuedCheque.PayeeType.SUPPLIER,
        party: Party | None = None,
        employee=None,
        expense_or_payable_account: Account | None = None,
        payment_voucher: Voucher | None = None,
        invoice_reference: str = "",
        project: Project | None = None,
        purpose: str = "",
        currency: str = "",
        exchange_rate: Decimal = Decimal("1.000000"),
        submit_for_approval: bool = False,
        authorized_by=None,
    ) -> IssuedCheque:
        if bank_account.company_id != company.id:
            raise ValidationError("Bank account does not belong to this company.")
        amt = Decimal(str(amount)).quantize(Decimal("0.01"))
        if amt <= 0:
            raise ValidationError("Issued cheque amount must be greater than zero.")

        chq_date = cheque_date or timezone.localdate()
        iss_date = issue_date or chq_date
        ccy = (currency or bank_account.currency or "NPR").upper()

        # Resolve / lock unique leaf
        if cheque_leaf is not None:
            leaf = ChequeLeaf.objects.select_for_update().get(pk=cheque_leaf.pk, company=company)
            if leaf.direction != ChequeLeaf.Direction.ISSUED:
                raise ValidationError("Selected cheque leaf is not an issued-series leaf.")
            if leaf.status not in (
                ChequeLeaf.Status.AVAILABLE,
                ChequeLeaf.Status.RESERVED,
                ChequeLeaf.Status.PREPARED,
                ChequeLeaf.Status.APPROVED,
            ):
                raise ValidationError(
                    f"Cheque leaf {leaf.cheque_number} is {leaf.status} and cannot be reused."
                )
        else:
            clean_num = (cheque_number or "").strip()
            if not clean_num:
                raise ValidationError("Select an available cheque leaf or supply cheque_number.")
            norm_no = normalize_cheque_number(clean_num)
            existing = ChequeLeaf.objects.filter(
                company=company,
                bank_account=bank_account,
                direction=ChequeLeaf.Direction.ISSUED,
                normalized_cheque_number=norm_no,
            ).first()
            if existing:
                if existing.status not in (ChequeLeaf.Status.AVAILABLE, ChequeLeaf.Status.RESERVED):
                    raise ValidationError(
                        f"Duplicate issued cheque blocked: {clean_num} already exists ({existing.status}) on {bank_account.account_name}."
                    )
                leaf = existing
            else:
                leaf = ChequeLeaf.objects.create(
                    company=company,
                    bank_account=bank_account,
                    cheque_book=cheque_book,
                    cheque_number=clean_num,
                    normalized_cheque_number=norm_no,
                    direction=ChequeLeaf.Direction.ISSUED,
                    status=ChequeLeaf.Status.AVAILABLE,
                )

        settings_obj = get_treasury_settings(company)
        needs_approval = bool(
            submit_for_approval
            or settings_obj.require_cheque_issue_approval
            or (amt * exchange_rate >= settings_obj.dual_auth_threshold_npr and not authorized_by)
        )

        # Post or attach Payment Voucher (Dr Sundry Creditors / Expense / Payable, Cr Bank GL)
        voucher = payment_voucher
        if not needs_approval and voucher is None:
            debit_acc = expense_or_payable_account or get_creditors_control_account(company, party=party)
            voucher = post_cheque_voucher(
                company=company,
                user=user,
                vtype=Voucher.VoucherType.PAYMENT,
                vdate=iss_date,
                project=project,
                party=party,
                reference_no=leaf.cheque_number,
                currency=ccy,
                exchange_rate=exchange_rate,
                narration=purpose or f"Cheque #{leaf.cheque_number} issued to {payee_name}",
                lines_data=[
                    {
                        "account": debit_acc,
                        "party": party if debit_acc.requires_subledger else None,
                        "debit": amt,
                        "credit": Decimal("0.00"),
                        "project": project,
                        "description": f"{invoice_reference or leaf.cheque_number} — {payee_name}",
                    },
                    {
                        "account": bank_account.gl_account,
                        "debit": Decimal("0.00"),
                        "credit": amt,
                        "project": project,
                        "description": f"Cheque #{leaf.cheque_number} ({payee_name})",
                    },
                ],
            )
        elif voucher is not None and voucher.company_id != company.id:
            raise ValidationError("Linked payment voucher belongs to another company.")

        prev_status = leaf.status
        target_leaf_status = ChequeLeaf.Status.PREPARED if needs_approval else ChequeLeaf.Status.ISSUED
        target_wf_status = (
            IssuedCheque.WorkflowStatus.PENDING_APPROVAL
            if needs_approval
            else IssuedCheque.WorkflowStatus.ISSUED
        )

        leaf.status = target_leaf_status
        leaf.party = party
        leaf.party_name = payee_name
        leaf.project = project
        leaf.purpose = purpose
        leaf.cheque_date = chq_date
        leaf.expected_presentation_date = expected_presentation_date
        leaf.amount = amt
        leaf.currency = ccy
        leaf.voucher = voucher
        leaf.signing_authority = authorized_by or (None if needs_approval else user)
        leaf.save()

        profile, _ = IssuedCheque.objects.update_or_create(
            leaf=leaf,
            defaults={
                "company": company,
                "cheque_book": leaf.cheque_book,
                "bank_account": bank_account,
                "payee_type": payee_type,
                "party": party,
                "employee": employee,
                "payee_name": payee_name,
                "amount": amt,
                "currency": ccy,
                "exchange_rate": exchange_rate,
                "cheque_date": chq_date,
                "issue_date": iss_date,
                "expected_presentation_date": expected_presentation_date,
                "payment_voucher": voucher,
                "invoice_reference": invoice_reference,
                "project": project,
                "purpose": purpose,
                "prepared_by": user,
                "authorized_by": authorized_by or (None if needs_approval else user),
                "workflow_status": target_wf_status,
            },
        )

        if needs_approval:
            approval_kind = (
                ChequeApproval.Kind.HIGH_VALUE_DUAL_SIGN
                if amt * exchange_rate >= settings_obj.dual_auth_threshold_npr
                else ChequeApproval.Kind.ISSUE_SIGN
            )
            ChequeApproval.objects.create(
                company=company,
                cheque_leaf=leaf,
                approval_kind=approval_kind,
                status=ChequeApproval.Status.PENDING,
                requested_by=user,
                payload={
                    "payee_name": payee_name,
                    "amount": str(amt),
                    "debit_account_id": str(expense_or_payable_account.id) if expense_or_payable_account else "",
                    "invoice_reference": invoice_reference,
                },
            )

        ChequeClearingEvent.objects.create(
            company=company,
            cheque_leaf=leaf,
            event_type=(
                ChequeClearingEvent.EventType.CREATED if needs_approval else ChequeClearingEvent.EventType.ISSUED
            ),
            event_date=iss_date,
            from_status=prev_status,
            to_status=target_leaf_status,
            voucher=voucher,
            actor=user,
            notes=purpose or f"Issued to {payee_name} ({amt} {ccy})",
        )
        ChequeBookService.sync_book_stock_status(leaf.cheque_book, actor=user)
        log_cheque_audit(
            company=company,
            action="ISSUED_CHEQUE_PREPARED" if needs_approval else "ISSUED_CHEQUE_POSTED",
            actor=user,
            cheque_leaf=leaf,
            previous_state={"status": prev_status},
            new_state={
                "status": target_leaf_status,
                "amount": str(amt),
                "payee_name": payee_name,
                "voucher_no": voucher.voucher_no if voucher else "",
            },
        )
        return profile

    @staticmethod
    @transaction.atomic
    def approve_and_issue(*, leaf: ChequeLeaf, approver, approve: bool = True, comment: str = "") -> IssuedCheque:
        leaf = ChequeLeaf.objects.select_for_update().get(pk=leaf.pk)
        profile = IssuedCheque.objects.select_for_update().get(leaf=leaf)
        enforce_maker_checker(
            maker=profile.prepared_by,
            checker=approver,
            allow_same_admin=True,
            action_label="cheque issuance",
        )
        pending = ChequeApproval.objects.filter(
            cheque_leaf=leaf, status=ChequeApproval.Status.PENDING
        ).first()

        if not approve:
            if pending:
                pending.status = ChequeApproval.Status.REJECTED
                pending.approved_by = approver
                pending.comment = comment
                pending.decided_at = timezone.now()
                pending.save()
            leaf.status = ChequeLeaf.Status.CANCELLED
            leaf.bounce_reason = comment or "Rejected during authorization"
            leaf.save(update_fields=["status", "bounce_reason", "updated_at"])
            profile.workflow_status = IssuedCheque.WorkflowStatus.CANCELLED
            profile.save(update_fields=["workflow_status", "updated_at"])
            return profile

        voucher = profile.payment_voucher or leaf.voucher
        if voucher is None:
            payload = pending.payload if pending else {}
            debit_acc = (
                Account.objects.filter(id=payload.get("debit_account_id"), company=leaf.company).first()
                if payload.get("debit_account_id")
                else None
            ) or get_creditors_control_account(leaf.company, party=profile.party)
            voucher = post_cheque_voucher(
                company=leaf.company,
                user=approver,
                vtype=Voucher.VoucherType.PAYMENT,
                vdate=profile.issue_date or timezone.localdate(),
                project=profile.project,
                party=profile.party,
                reference_no=leaf.cheque_number,
                currency=profile.currency,
                exchange_rate=profile.exchange_rate,
                narration=profile.purpose or f"Cheque #{leaf.cheque_number} issued to {profile.payee_name}",
                lines_data=[
                    {
                        "account": debit_acc,
                        "party": profile.party if debit_acc.requires_subledger else None,
                        "debit": profile.amount,
                        "credit": Decimal("0.00"),
                        "project": profile.project,
                        "description": f"{profile.invoice_reference or leaf.cheque_number} — {profile.payee_name}",
                    },
                    {
                        "account": profile.bank_account.gl_account,
                        "debit": Decimal("0.00"),
                        "credit": profile.amount,
                        "project": profile.project,
                        "description": f"Cheque #{leaf.cheque_number} ({profile.payee_name})",
                    },
                ],
            )
            leaf.voucher = voucher
            profile.payment_voucher = voucher

        if pending:
            pending.status = ChequeApproval.Status.APPROVED
            pending.approved_by = approver
            pending.comment = comment
            pending.decided_at = timezone.now()
            pending.save()

        prev = leaf.status
        leaf.status = ChequeLeaf.Status.ISSUED
        leaf.signing_authority = approver
        leaf.save(update_fields=["status", "voucher", "signing_authority", "updated_at"])

        profile.authorized_by = approver
        profile.workflow_status = IssuedCheque.WorkflowStatus.ISSUED
        profile.save(update_fields=["authorized_by", "payment_voucher", "workflow_status", "updated_at"])

        ChequeClearingEvent.objects.create(
            company=leaf.company,
            cheque_leaf=leaf,
            event_type=ChequeClearingEvent.EventType.ISSUED,
            event_date=timezone.localdate(),
            from_status=prev,
            to_status=ChequeLeaf.Status.ISSUED,
            voucher=voucher,
            actor=approver,
            notes=comment or "Authorized & issued",
        )
        log_cheque_audit(
            company=leaf.company,
            action="ISSUED_CHEQUE_AUTHORIZED",
            actor=approver,
            cheque_leaf=leaf,
            previous_state={"status": prev},
            new_state={"status": ChequeLeaf.Status.ISSUED, "voucher_no": voucher.voucher_no if voucher else ""},
        )
        return profile

    @staticmethod
    @transaction.atomic
    def stop_payment(
        *,
        leaf: ChequeLeaf,
        user,
        reason: str,
        stop_date: date | None = None,
        bank_stop_ref: str = "",
    ) -> ChequeLeaf:
        leaf = ChequeLeaf.objects.select_for_update().get(pk=leaf.pk)
        if leaf.direction != ChequeLeaf.Direction.ISSUED:
            raise ValidationError("Stop payment only applies to issued company cheques.")
        if leaf.status in (ChequeLeaf.Status.CLEARED, ChequeLeaf.Status.CANCELLED):
            raise ValidationError(f"Cheque in status {leaf.status} cannot undergo stop payment.")
        if not (reason or "").strip():
            raise ValidationError("Provide a reason for stop-payment instruction.")

        d = stop_date or timezone.localdate()
        prev = leaf.status
        rev_voucher = None
        if leaf.voucher and leaf.voucher.status == Voucher.Status.POSTED and not leaf.reversal_voucher_id:
            OpenItemSyncService.release_allocations_for_reversal(
                voucher=leaf.voucher, reason=f"Stop payment on cheque #{leaf.cheque_number}"
            )
            rev_voucher = PostingService.reverse_voucher(
                voucher=leaf.voucher,
                user=user,
                reversal_date=d,
                reason=f"Stop payment #{leaf.cheque_number}: {reason}",
            )
            leaf.reversal_voucher = rev_voucher

        leaf.status = ChequeLeaf.Status.STOP_PAYMENT
        leaf.bounce_reason = reason.strip()
        leaf.save(update_fields=["status", "reversal_voucher", "bounce_reason", "updated_at"])

        if hasattr(leaf, "issued_profile"):
            prof = leaf.issued_profile
            prof.workflow_status = IssuedCheque.WorkflowStatus.STOP_PAYMENT
            prof.stop_payment_ref = bank_stop_ref
            prof.stop_payment_date = d
            prof.save(update_fields=["workflow_status", "stop_payment_ref", "stop_payment_date", "updated_at"])

        ChequeCancellation.objects.create(
            company=leaf.company,
            cheque_leaf=leaf,
            cancellation_kind=ChequeCancellation.CancellationKind.STOP_PAYMENT,
            reason=reason.strip(),
            bank_stop_ref=bank_stop_ref,
            requested_by=user,
            approved_by=user,
            reversal_voucher=rev_voucher,
        )
        ChequeClearingEvent.objects.create(
            company=leaf.company,
            cheque_leaf=leaf,
            event_type=ChequeClearingEvent.EventType.STOP_PAYMENT,
            event_date=d,
            from_status=prev,
            to_status=ChequeLeaf.Status.STOP_PAYMENT,
            voucher=rev_voucher,
            bank_reference=bank_stop_ref,
            actor=user,
            notes=reason.strip(),
        )
        log_cheque_audit(
            company=leaf.company,
            action="CHEQUE_STOP_PAYMENT",
            actor=user,
            cheque_leaf=leaf,
            previous_state={"status": prev},
            new_state={"status": ChequeLeaf.Status.STOP_PAYMENT, "bank_stop_ref": bank_stop_ref},
            notes=reason.strip(),
        )
        return leaf

    @staticmethod
    def build_print_payload(leaf: ChequeLeaf) -> dict:
        prof = getattr(leaf, "issued_profile", None)
        return {
            "cheque_number": leaf.cheque_number,
            "bank_name": leaf.bank_account.bank_branch.bank.name if leaf.bank_account.bank_branch else "",
            "branch_name": leaf.bank_account.bank_branch.name if leaf.bank_account.bank_branch else "",
            "account_name": leaf.bank_account.account_name,
            "account_masked": leaf.bank_account.account_number_masked,
            "payee_name": prof.payee_name if prof else leaf.party_name,
            "amount": str(leaf.amount),
            "currency": leaf.currency,
            "cheque_date": leaf.cheque_date.isoformat() if leaf.cheque_date else "",
            "issue_date": (prof.issue_date.isoformat() if prof and prof.issue_date else ""),
            "voucher_no": leaf.voucher.voucher_no if leaf.voucher else "",
            "invoice_reference": prof.invoice_reference if prof else "",
            "purpose": leaf.purpose,
            "status": leaf.status,
            "account_payee_only": True,
        }

