import csv
import io
from datetime import timedelta
from decimal import Decimal
from django.db.models import Count, Q, Sum
from django.utils import timezone

from apps.banking.models import BankAccount, ChequeBook, ChequeLeaf
from apps.treasury.cheques.gl_helpers import get_treasury_settings
from apps.treasury.cheques.models import (
    ChequeAlert,
    ChequeApproval,
    ChequeCancellation,
    ChequeDepositBatch,
    ChequeReplacement,
    ChequeReturn,
    ChequeReversal,
)
from apps.treasury.cheques.reversals.service import ChequeReversalEngine

CHEQUE_REPORT_TYPES = [
    {"code": "CHEQUE_BOOK_REGISTER", "label": "Cheque Book Register"},
    {"code": "UNUSED_CHEQUE_LEAVES", "label": "Unused Cheque Leaves"},
    {"code": "ISSUED_CHEQUE_REGISTER", "label": "Issued Cheque Register"},
    {"code": "RECEIVED_CHEQUE_REGISTER", "label": "Received Cheque Register"},
    {"code": "CHEQUES_IN_HAND_LEDGER", "label": "Cheques-in-Hand Ledger (1035)"},
    {"code": "CHEQUES_IN_CLEARING_LEDGER", "label": "Cheques-in-Clearing Ledger (1036)"},
    {"code": "CLEARED_CHEQUES", "label": "Cleared Cheques Register"},
    {"code": "OUTSTANDING_ISSUED_CHEQUES", "label": "Outstanding Issued Cheques"},
    {"code": "BOUNCED_CHEQUES", "label": "Bounced Cheques Register"},
    {"code": "CANCELLED_CHEQUES", "label": "Cancelled & Stop-Payment Cheques"},
    {"code": "DEPOSIT_BATCH_REGISTER", "label": "Deposit Batch Register"},
    {"code": "CHEQUE_RETURN_CHARGES", "label": "Cheque Return Charges Register"},
    {"code": "BANK_WISE_CLEARING", "label": "Bank-Wise Clearing Performance"},
    {"code": "PARTY_WISE_CHEQUES", "label": "Party-Wise Cheque History"},
]


class ChequeReportingService:
    @staticmethod
    def build_dashboard(*, company) -> dict:
        today = timezone.localdate()
        month_start = today.replace(day=1)
        settings_obj = get_treasury_settings(company)
        stale_cutoff = today - timedelta(days=int(settings_obj.stale_cheque_days or 180))
        delay_cutoff = today - timedelta(days=int(settings_obj.clearing_delay_alert_days or 5))

        books = ChequeBook.objects.select_related("bank_account").filter(company=company)
        active_books = books.filter(status=ChequeBook.BookStatus.ACTIVE).count()
        total_remaining_leaves = ChequeLeaf.objects.filter(
            company=company, direction=ChequeLeaf.Direction.ISSUED, status=ChequeLeaf.Status.AVAILABLE
        ).count()

        issued_qs = ChequeLeaf.objects.filter(company=company, direction=ChequeLeaf.Direction.ISSUED).exclude(
            status=ChequeLeaf.Status.AVAILABLE
        )
        received_qs = ChequeLeaf.objects.filter(company=company, direction=ChequeLeaf.Direction.RECEIVED)

        issued_outstanding = issued_qs.filter(
            status__in=[ChequeLeaf.Status.ISSUED, ChequeLeaf.Status.PRESENTED, ChequeLeaf.Status.APPROVED]
        )
        in_hand_qs = received_qs.filter(
            status__in=[ChequeLeaf.Status.IN_HAND, ChequeLeaf.Status.RECEIVED, ChequeLeaf.Status.VERIFIED]
        )
        under_clearing_qs = received_qs.filter(
            status__in=[ChequeLeaf.Status.DEPOSITED, ChequeLeaf.Status.UNDER_CLEARING]
        )
        cleared_this_month = ChequeLeaf.objects.filter(
            company=company, status=ChequeLeaf.Status.CLEARED, cleared_date__gte=month_start
        )
        bounced_qs = ChequeLeaf.objects.filter(company=company, status=ChequeLeaf.Status.BOUNCED)
        cancelled_qs = ChequeLeaf.objects.filter(
            company=company,
            status__in=[ChequeLeaf.Status.CANCELLED, ChequeLeaf.Status.STOP_PAYMENT, ChequeLeaf.Status.LOST_DAMAGED],
        )

        # Upcoming cheque dates (next 15 days)
        upcoming = list(
            ChequeLeaf.objects.select_related("bank_account")
            .filter(
                company=company,
                status__in=[
                    ChequeLeaf.Status.ISSUED,
                    ChequeLeaf.Status.PRESENTED,
                    ChequeLeaf.Status.IN_HAND,
                    ChequeLeaf.Status.UNDER_CLEARING,
                ],
                cheque_date__isnull=False,
                cheque_date__gte=today,
                cheque_date__lte=today + timedelta(days=15),
            )
            .order_by("cheque_date")[:12]
        )

        # Bank-wise clearing performance
        bank_perf = []
        for ba in BankAccount.objects.select_related("bank_branch__bank").filter(company=company, status="ACTIVE"):
            ba_rec = received_qs.filter(bank_account=ba)
            cleared_cnt = ba_rec.filter(status=ChequeLeaf.Status.CLEARED).count()
            bounced_cnt = ba_rec.filter(status=ChequeLeaf.Status.BOUNCED).count()
            in_hand_amt = ba_rec.filter(
                status__in=[ChequeLeaf.Status.IN_HAND, ChequeLeaf.Status.VERIFIED, ChequeLeaf.Status.RECEIVED]
            ).aggregate(t=Sum("amount"))["t"] or Decimal("0.00")
            clearing_amt = ba_rec.filter(
                status__in=[ChequeLeaf.Status.DEPOSITED, ChequeLeaf.Status.UNDER_CLEARING]
            ).aggregate(t=Sum("amount"))["t"] or Decimal("0.00")
            issued_out_amt = issued_outstanding.filter(bank_account=ba).aggregate(t=Sum("amount"))["t"] or Decimal("0.00")
            bank_perf.append(
                {
                    "bank_account_id": str(ba.id),
                    "account_name": ba.account_name,
                    "bank_name": ba.bank_branch.bank.name if ba.bank_branch else "",
                    "currency": ba.currency,
                    "in_hand_amount": str(in_hand_amt),
                    "under_clearing_amount": str(clearing_amt),
                    "issued_outstanding_amount": str(issued_out_amt),
                    "cleared_count": cleared_cnt,
                    "bounced_count": bounced_cnt,
                }
            )

        reconciliation = ChequeReversalEngine.reconcile_subledger_with_gl(company=company)
        stale_candidates = ChequeLeaf.objects.filter(
            company=company,
            status__in=[ChequeLeaf.Status.ISSUED, ChequeLeaf.Status.IN_HAND, ChequeLeaf.Status.VERIFIED],
            cheque_date__lte=stale_cutoff,
        ).count()
        delayed_clearing = under_clearing_qs.filter(deposit_date__lte=delay_cutoff).count()
        pending_approvals = ChequeApproval.objects.filter(
            company=company, status=ChequeApproval.Status.PENDING
        ).count()
        active_alerts = ChequeAlert.objects.filter(company=company, is_resolved=False).count()

        def sum_amt(qs):
            return str(qs.aggregate(t=Sum("amount"))["t"] or Decimal("0.00"))

        return {
            "kpis": {
                "active_cheque_books": active_books,
                "remaining_leaves": total_remaining_leaves,
                "issued_count": issued_qs.count(),
                "issued_total_amount": sum_amt(issued_qs),
                "issued_outstanding_count": issued_outstanding.count(),
                "issued_outstanding_amount": sum_amt(issued_outstanding),
                "received_count": received_qs.count(),
                "received_total_amount": sum_amt(received_qs),
                "cheques_in_hand_count": in_hand_qs.count(),
                "cheques_in_hand_amount": sum_amt(in_hand_qs),
                "under_clearing_count": under_clearing_qs.count(),
                "under_clearing_amount": sum_amt(under_clearing_qs),
                "cleared_this_month_count": cleared_this_month.count(),
                "cleared_this_month_amount": sum_amt(cleared_this_month),
                "bounced_count": bounced_qs.count(),
                "bounced_amount": sum_amt(bounced_qs),
                "cancelled_count": cancelled_qs.count(),
                "stale_count": stale_candidates,
                "delayed_clearing_count": delayed_clearing,
                "pending_approvals": pending_approvals,
                "active_alerts": active_alerts,
            },
            "gl_reconciliation": reconciliation,
            "bank_performance": bank_perf,
            "upcoming_cheques": [
                {
                    "id": str(c.id),
                    "cheque_number": c.cheque_number,
                    "direction": c.direction,
                    "party_name": c.party_name or c.drawer_name,
                    "bank_account_name": c.bank_account.account_name,
                    "cheque_date": c.cheque_date.isoformat() if c.cheque_date else "",
                    "amount": str(c.amount),
                    "currency": c.currency,
                    "status": c.status,
                }
                for c in upcoming
            ],
        }

    @staticmethod
    def scan_and_refresh_alerts(*, company) -> int:
        today = timezone.localdate()
        settings_obj = get_treasury_settings(company)
        stale_cutoff = today - timedelta(days=int(settings_obj.stale_cheque_days or 180))
        delay_cutoff = today - timedelta(days=int(settings_obj.clearing_delay_alert_days or 5))
        created = 0

        for chq in ChequeLeaf.objects.filter(
            company=company,
            status__in=[ChequeLeaf.Status.ISSUED, ChequeLeaf.Status.IN_HAND, ChequeLeaf.Status.VERIFIED],
            cheque_date__lte=stale_cutoff,
        ):
            _, was_created = ChequeAlert.objects.get_or_create(
                company=company,
                cheque_leaf=chq,
                alert_type=ChequeAlert.AlertType.STALE_CHEQUE,
                is_resolved=False,
                defaults={
                    "severity": ChequeAlert.Severity.WARNING,
                    "title": f"Stale-Dated Cheque #{chq.cheque_number}",
                    "message": f"Cheque #{chq.cheque_number} ({chq.cheque_date}) exceeded {settings_obj.stale_cheque_days} days.",
                },
            )
            if was_created:
                created += 1

        for chq in ChequeLeaf.objects.filter(
            company=company,
            direction=ChequeLeaf.Direction.RECEIVED,
            status__in=[ChequeLeaf.Status.DEPOSITED, ChequeLeaf.Status.UNDER_CLEARING],
            deposit_date__lte=delay_cutoff,
        ):
            _, was_created = ChequeAlert.objects.get_or_create(
                company=company,
                cheque_leaf=chq,
                alert_type=ChequeAlert.AlertType.CLEARING_DELAYED,
                is_resolved=False,
                defaults={
                    "severity": ChequeAlert.Severity.WARNING,
                    "title": f"Clearing Delayed #{chq.cheque_number}",
                    "message": f"Deposited {chq.deposit_date} to {chq.bank_account.account_name}; still awaiting clearance.",
                },
            )
            if was_created:
                created += 1
        return created

    @staticmethod
    def generate_report(*, company, report_type: str, filters: dict) -> dict:
        code = (report_type or "ISSUED_CHEQUE_REGISTER").upper()
        ba_id = filters.get("bank_account")
        party_id = filters.get("party")
        project_id = filters.get("project")
        status_filter = filters.get("status")
        branch_id = filters.get("branch")
        date_from = filters.get("date_from")
        date_to = filters.get("date_to")

        def filter_leaves(qs):
            if ba_id:
                qs = qs.filter(bank_account_id=ba_id)
            if party_id:
                qs = qs.filter(party_id=party_id)
            if project_id:
                qs = qs.filter(project_id=project_id)
            if branch_id:
                qs = qs.filter(bank_account__branch_id=branch_id)
            if status_filter:
                qs = qs.filter(status=status_filter)
            if date_from:
                qs = qs.filter(cheque_date__gte=date_from)
            if date_to:
                qs = qs.filter(cheque_date__lte=date_to)
            return qs

        rows: list[dict] = []
        if code == "CHEQUE_BOOK_REGISTER":
            books = ChequeBook.objects.select_related("bank_account", "assigned_to").filter(company=company)
            if ba_id:
                books = books.filter(bank_account_id=ba_id)
            for b in books:
                tot = b.end_number - b.start_number + 1
                rem = b.leaves.filter(status=ChequeLeaf.Status.AVAILABLE).count()
                rows.append(
                    {
                        "book_code": b.book_code,
                        "bank_book_number": b.bank_book_number,
                        "bank_account": b.bank_account.account_name,
                        "range": f"{b.prefix}{b.start_number} - {b.prefix}{b.end_number}",
                        "total_leaves": tot,
                        "remaining_leaves": rem,
                        "custodian": b.assigned_to.username if b.assigned_to else "-",
                        "issued_date": b.issued_date.isoformat(),
                        "status": b.status,
                    }
                )
        elif code == "UNUSED_CHEQUE_LEAVES":
            qs = filter_leaves(
                ChequeLeaf.objects.select_related("bank_account", "cheque_book")
                .filter(company=company, direction=ChequeLeaf.Direction.ISSUED, status=ChequeLeaf.Status.AVAILABLE)
            )
            for l in qs[:500]:
                rows.append(
                    {
                        "cheque_no": l.cheque_number,
                        "book_code": l.cheque_book.book_code if l.cheque_book else "-",
                        "bank_account": l.bank_account.account_name,
                        "custodian": l.cheque_book.assigned_to.username if l.cheque_book and l.cheque_book.assigned_to else "-",
                        "status": l.status,
                    }
                )
        elif code == "DEPOSIT_BATCH_REGISTER":
            batches = ChequeDepositBatch.objects.select_related("deposit_bank_account", "prepared_by").filter(company=company)
            if ba_id:
                batches = batches.filter(deposit_bank_account_id=ba_id)
            for b in batches[:300]:
                rows.append(
                    {
                        "batch_no": b.batch_no,
                        "deposit_date": b.deposit_date.isoformat(),
                        "deposit_slip": b.deposit_slip_no,
                        "bank_account": b.deposit_bank_account.account_name,
                        "cheque_count": b.cheque_count,
                        "total_amount": str(b.total_amount),
                        "status": b.status,
                        "prepared_by": b.prepared_by.username if b.prepared_by else "",
                    }
                )
        elif code == "CHEQUE_RETURN_CHARGES":
            returns = ChequeReturn.objects.select_related("cheque_leaf", "charge_voucher").filter(
                company=company, bank_charge_amount__gt=0
            )
            for r in returns[:300]:
                rows.append(
                    {
                        "bounce_date": r.bounce_date.isoformat(),
                        "cheque_no": r.cheque_leaf.cheque_number,
                        "scenario": r.bounce_scenario,
                        "return_reference": r.bank_return_reference,
                        "bank_charge": str(r.bank_charge_amount),
                        "charge_voucher": r.charge_voucher.voucher_no if r.charge_voucher else "",
                        "reason": r.return_reason,
                    }
                )
        elif code == "BANK_WISE_CLEARING":
            rows = ChequeReportingService.build_dashboard(company=company)["bank_performance"]
        elif code == "PARTY_WISE_CHEQUES":
            qs = filter_leaves(
                ChequeLeaf.objects.select_related("bank_account", "party", "voucher").filter(company=company)
                .exclude(status=ChequeLeaf.Status.AVAILABLE)
            ).order_by("party_name", "-cheque_date")
            for l in qs[:500]:
                rows.append(
                    {
                        "party": l.party_name or l.drawer_name or "-",
                        "direction": l.direction,
                        "cheque_no": l.cheque_number,
                        "bank_account": l.bank_account.account_name,
                        "cheque_date": l.cheque_date.isoformat() if l.cheque_date else "",
                        "amount": str(l.amount),
                        "currency": l.currency,
                        "status": l.status,
                        "voucher_no": l.voucher.voucher_no if l.voucher else "",
                    }
                )
        else:
            qs = ChequeLeaf.objects.select_related(
                "bank_account", "party", "project", "voucher", "clearing_voucher", "reversal_voucher"
            ).filter(company=company).exclude(status=ChequeLeaf.Status.AVAILABLE)
            if code == "ISSUED_CHEQUE_REGISTER":
                qs = qs.filter(direction=ChequeLeaf.Direction.ISSUED)
            elif code == "RECEIVED_CHEQUE_REGISTER":
                qs = qs.filter(direction=ChequeLeaf.Direction.RECEIVED)
            elif code == "CHEQUES_IN_HAND_LEDGER":
                qs = qs.filter(
                    direction=ChequeLeaf.Direction.RECEIVED,
                    status__in=[ChequeLeaf.Status.IN_HAND, ChequeLeaf.Status.RECEIVED, ChequeLeaf.Status.VERIFIED],
                )
            elif code == "CHEQUES_IN_CLEARING_LEDGER":
                qs = qs.filter(
                    direction=ChequeLeaf.Direction.RECEIVED,
                    status__in=[ChequeLeaf.Status.DEPOSITED, ChequeLeaf.Status.UNDER_CLEARING],
                )
            elif code == "CLEARED_CHEQUES":
                qs = qs.filter(status=ChequeLeaf.Status.CLEARED)
            elif code == "OUTSTANDING_ISSUED_CHEQUES":
                qs = qs.filter(
                    direction=ChequeLeaf.Direction.ISSUED,
                    status__in=[ChequeLeaf.Status.ISSUED, ChequeLeaf.Status.PRESENTED, ChequeLeaf.Status.APPROVED],
                    bank_reconciled=False,
                )
            elif code == "BOUNCED_CHEQUES":
                qs = qs.filter(status=ChequeLeaf.Status.BOUNCED)
            elif code == "CANCELLED_CHEQUES":
                qs = qs.filter(
                    status__in=[ChequeLeaf.Status.CANCELLED, ChequeLeaf.Status.STOP_PAYMENT, ChequeLeaf.Status.SKIPPED, ChequeLeaf.Status.LOST_DAMAGED]
                )

            qs = filter_leaves(qs)
            for l in qs[:500]:
                rows.append(
                    {
                        "cheque_no": l.cheque_number,
                        "direction": l.direction,
                        "bank_account": l.bank_account.account_name,
                        "party_or_drawer": l.party_name or l.drawer_name or "-",
                        "drawer_bank": l.drawer_bank or "-",
                        "project": l.project.code if l.project else "-",
                        "cheque_date": l.cheque_date.isoformat() if l.cheque_date else "",
                        "deposit_date": l.deposit_date.isoformat() if l.deposit_date else "",
                        "cleared_date": l.cleared_date.isoformat() if l.cleared_date else "",
                        "amount": str(l.amount),
                        "currency": l.currency,
                        "status": l.status,
                        "voucher_no": l.voucher.voucher_no if l.voucher else "",
                        "clearing_voucher_no": l.clearing_voucher.voucher_no if l.clearing_voucher else "",
                        "reversal_voucher_no": l.reversal_voucher.voucher_no if l.reversal_voucher else "",
                        "reason": l.bounce_reason,
                    }
                )

        return {"report_type": code, "count": len(rows), "rows": rows}

    @staticmethod
    def export_csv(rows: list[dict]) -> bytes:
        buf = io.StringIO()
        if not rows:
            buf.write("No records found\n")
            return buf.getvalue().encode("utf-8")
        headers = list(rows[0].keys())
        writer = csv.DictWriter(buf, fieldnames=headers)
        writer.writeheader()
        for r in rows:
            writer.writerow(r)
        return buf.getvalue().encode("utf-8")

    @staticmethod
    def export_xlsx(title: str, rows: list[dict]) -> bytes:
        import openpyxl

        wb = openpyxl.Workbook()
        ws = wb.active
        ws.title = title[:31]
        if not rows:
            ws.append(["No records found"])
        else:
            headers = list(rows[0].keys())
            ws.append([h.replace("_", " ").title() for h in headers])
            for r in rows:
                ws.append([r.get(h, "") for h in headers])
        bio = io.BytesIO()
        wb.save(bio)
        return bio.getvalue()

