from decimal import Decimal
from django.db import transaction
from django.db.models import F, Sum
from django.utils import timezone

from apps.accounting.models import Account, LedgerEntry, Party, PartyLedgerEntry
from apps.accounting.services.subledger_service import SubledgerService
from apps.party_hub.models import OpenItem, PartyReconciliationException, PartyReconciliationRun


class PartyReconciliationService:
    """
    Runs end-to-end GL Control Account vs. Party Subledger vs. OpenItem reconciliation
    covering Debtors, Creditors, Subcontractors, Retention, and Advances.
    """

    MONITORED_ROLES = [
        Account.ControlRole.SUNDRY_DEBTORS,
        Account.ControlRole.SUNDRY_CREDITORS,
        Account.ControlRole.SUBCONTRACTOR_PAYABLE,
        Account.ControlRole.RETENTION_RECEIVABLE,
        Account.ControlRole.RETENTION_PAYABLE,
        Account.ControlRole.CUSTOMER_ADVANCE,
        Account.ControlRole.SUPPLIER_ADVANCE,
    ]

    @staticmethod
    def get_control_account_matrix(company) -> list[dict]:
        rows = []
        for role in PartyReconciliationService.MONITORED_ROLES:
            rec = SubledgerService.reconcile_control_account(company, role)
            # Also compare open items net for trade control accounts
            open_net = Decimal("0.00")
            if role in (Account.ControlRole.SUNDRY_DEBTORS,):
                for oi in OpenItem.objects.filter(
                    company=company, control_account__control_role=role
                ).exclude(status=OpenItem.Status.REVERSED):
                    sign = Decimal("-1") if oi.is_unallocated_credit else Decimal("1")
                    open_net += sign * oi.remaining_amount
            elif role in (Account.ControlRole.SUNDRY_CREDITORS, Account.ControlRole.SUBCONTRACTOR_PAYABLE):
                for oi in OpenItem.objects.filter(
                    company=company, control_account__control_role=role
                ).exclude(status=OpenItem.Status.REVERSED):
                    sign = Decimal("1") if oi.is_unallocated_credit else Decimal("-1")
                    open_net += sign * oi.remaining_amount
            rec["open_items_net"] = str(open_net)
            rows.append(rec)
        return rows

    @staticmethod
    @transaction.atomic
    def run_reconciliation(*, company, user, as_of_date=None) -> PartyReconciliationRun:
        as_of_date = as_of_date or timezone.localdate()
        matrix = PartyReconciliationService.get_control_account_matrix(company)
        count = PartyReconciliationRun.objects.filter(company=company).count() + 1
        run_no = f"REC-{as_of_date.strftime('%Y%m%d')}-{count:04d}"

        exceptions_to_create = []
        for row in matrix:
            diff = Decimal(row["difference"])
            if diff != Decimal("0.00"):
                exceptions_to_create.append(
                    {
                        "control_role": row["control_role"],
                        "account_code": row.get("account_code", ""),
                        "gl_amount": Decimal(row["gl_balance"]),
                        "subledger_amount": Decimal(row["subledger_balance"]),
                        "variance_amount": diff,
                        "severity": PartyReconciliationException.Severity.CRITICAL,
                        "description": f"GL vs Subledger mismatch of {diff} on {row['control_role']} ({row.get('account_code')}).",
                    }
                )

        # Check orphaned GL postings on control accounts without a party reference
        orphan_entries = LedgerEntry.objects.select_related("account", "voucher").filter(
            company=company,
            account__control_role__in=PartyReconciliationService.MONITORED_ROLES,
            party__isnull=True,
        )[:25]
        for oe in orphan_entries:
            net_oe = oe.base_debit - oe.base_credit
            if net_oe != 0:
                exceptions_to_create.append(
                    {
                        "control_role": oe.account.control_role,
                        "account_code": oe.account.code,
                        "gl_amount": net_oe,
                        "subledger_amount": Decimal("0.00"),
                        "variance_amount": net_oe,
                        "severity": PartyReconciliationException.Severity.WARNING,
                        "description": f"Unreferenced control posting in voucher {oe.voucher.voucher_no} on {oe.account.code}.",
                    }
                )

        run = PartyReconciliationRun.objects.create(
            company=company,
            run_no=run_no,
            as_of_date=as_of_date,
            is_reconciled=len(exceptions_to_create) == 0,
            exception_count=len(exceptions_to_create),
            summary_payload={"control_accounts": matrix},
            run_by=user,
        )
        for ex in exceptions_to_create:
            PartyReconciliationException.objects.create(reconciliation_run=run, **ex)

        return run
