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

from apps.banking.models import BankAccount, ChequeBook, ChequeLeaf, normalize_cheque_number
from apps.treasury.cheques.audit import log_cheque_audit
from apps.treasury.cheques.models import ChequeAlert, ChequeClearingEvent


class ChequeBookService:
    @staticmethod
    @transaction.atomic
    def register_book(
        *,
        company,
        bank_account: BankAccount,
        book_code: str,
        start_number: int,
        end_number: int,
        issued_date: date,
        prefix: str = "",
        bank_book_number: str = "",
        assigned_to=None,
        low_stock_threshold: int = 5,
        handover_notes: str = "",
        actor=None,
    ) -> ChequeBook:
        if bank_account.company_id != company.id:
            raise ValidationError("Bank account does not belong to this company.")
        if end_number < start_number or (end_number - start_number) > 500:
            raise ValidationError("Cheque book range must be between 1 and 500 leaves.")

        clean_prefix = (prefix or "").strip()
        # Prevent overlapping active/exhausted/suspended cheque ranges for the same issuing account & prefix
        existing_books = ChequeBook.objects.filter(
            company=company, bank_account=bank_account, prefix=clean_prefix
        ).exclude(status=ChequeBook.BookStatus.CANCELLED)
        for existing in existing_books:
            if not (end_number < existing.start_number or start_number > existing.end_number):
                raise ValidationError(
                    f"Overlapping cheque range [{start_number}..{end_number}] conflicts with existing book "
                    f"{existing.book_code} [{existing.start_number}..{existing.end_number}]."
                )

        book = ChequeBook.objects.create(
            company=company,
            bank_account=bank_account,
            book_code=book_code.strip(),
            bank_book_number=bank_book_number.strip(),
            prefix=clean_prefix,
            start_number=start_number,
            end_number=end_number,
            issued_date=issued_date,
            assigned_to=assigned_to,
            low_stock_threshold=low_stock_threshold,
            handover_notes=handover_notes,
            last_handed_over_at=timezone.now() if assigned_to else None,
        )

        width = max(len(str(end_number)), 6 if not clean_prefix else len(str(end_number)))
        leaves_to_create = []
        norm_numbers = []
        for num in range(start_number, end_number + 1):
            chq_no = f"{clean_prefix}{str(num).zfill(width)}"
            norm_no = normalize_cheque_number(chq_no)
            norm_numbers.append(norm_no)
            leaves_to_create.append(
                ChequeLeaf(
                    company=company,
                    bank_account=bank_account,
                    cheque_book=book,
                    cheque_number=chq_no,
                    normalized_cheque_number=norm_no,
                    issued_unique_key=norm_no,
                    direction=ChequeLeaf.Direction.ISSUED,
                    status=ChequeLeaf.Status.AVAILABLE,
                )
            )

        if ChequeLeaf.objects.filter(
            company=company,
            bank_account=bank_account,
            direction=ChequeLeaf.Direction.ISSUED,
            normalized_cheque_number__in=norm_numbers,
        ).exists():
            raise ValidationError("One or more cheque numbers already exist for this bank account.")

        created_leaves = ChequeLeaf.objects.bulk_create(leaves_to_create)
        ChequeClearingEvent.objects.bulk_create(
            [
                ChequeClearingEvent(
                    company=company,
                    cheque_leaf=lf,
                    event_type=ChequeClearingEvent.EventType.CREATED,
                    event_date=issued_date,
                    from_status="",
                    to_status=ChequeLeaf.Status.AVAILABLE,
                    actor=actor,
                    notes=f"Registered in book {book.book_code}",
                )
                for lf in created_leaves
            ]
        )
        log_cheque_audit(
            company=company,
            action="CHEQUE_BOOK_REGISTERED",
            actor=actor,
            cheque_book=book,
            new_state={
                "book_code": book.book_code,
                "range": f"{start_number}..{end_number}",
                "total_leaves": len(created_leaves),
                "assigned_to": assigned_to.username if assigned_to else "",
            },
            notes=f"Registered {len(created_leaves)} leaves on {bank_account.account_name}",
        )
        return book

    @staticmethod
    @transaction.atomic
    def handover_book(*, book: ChequeBook, new_custodian, actor, notes: str = "") -> ChequeBook:
        prev_user = book.assigned_to.username if book.assigned_to else ""
        book.assigned_to = new_custodian
        book.handover_notes = notes or book.handover_notes
        book.last_handed_over_at = timezone.now()
        book.save(update_fields=["assigned_to", "handover_notes", "last_handed_over_at", "updated_at"])
        log_cheque_audit(
            company=book.company,
            action="CHEQUE_BOOK_HANDOVER",
            actor=actor,
            cheque_book=book,
            previous_state={"assigned_to": prev_user},
            new_state={"assigned_to": new_custodian.username if new_custodian else ""},
            notes=notes or "Cheque book custody handover",
        )
        return book

    @staticmethod
    def sync_book_stock_status(book: ChequeBook, actor=None):
        if not book:
            return
        remaining = book.leaves.filter(status=ChequeLeaf.Status.AVAILABLE).count()
        if remaining == 0 and book.status == ChequeBook.BookStatus.ACTIVE:
            book.status = ChequeBook.BookStatus.EXHAUSTED
            book.save(update_fields=["status", "updated_at"])
        if remaining <= book.low_stock_threshold and book.status == ChequeBook.BookStatus.ACTIVE:
            ChequeAlert.objects.get_or_create(
                company=book.company,
                cheque_book=book,
                alert_type=ChequeAlert.AlertType.LOW_BOOK_STOCK,
                is_resolved=False,
                defaults={
                    "severity": ChequeAlert.Severity.CRITICAL if remaining <= 2 else ChequeAlert.Severity.WARNING,
                    "title": f"Low Cheque Leaves: {book.book_code}",
                    "message": f"Only {remaining} unused leaves remain in {book.book_code} ({book.bank_account.account_name}).",
                },
            )

