from decimal import Decimal
from django.core.exceptions import ValidationError
from django.db.models import Q, Sum
from django.utils import timezone

from apps.accounting.models import (
    Account,
    AccountRelationship,
    AdvanceAdjustment,
    AdvanceRecord,
    BillAllocation,
    BoqItem,
    Department,
    EmployeeProfile,
    LedgerEntry,
    Party,
    PartyLedgerEntry,
    PayrollLiability,
    StaffLoan,
    Voucher,
    VoucherLine,
)
from apps.banking.models import BankAccount, CashAccount
from apps.localization.bs_calendar import ad_to_bs
from apps.projects.models import CostCode, Project, Site


class AccountIntelligenceService:
    """Database-driven account-to-subledger, child-ledger, employee & advance relationship resolver."""

    @staticmethod
    def _current_gl_balance(company, account: Account) -> Decimal:
        agg = LedgerEntry.objects.filter(company=company, account=account).aggregate(
            d=Sum("base_debit"), c=Sum("base_credit")
        )
        d = (agg["d"] or Decimal("0.00")) + account.opening_debit
        c = (agg["c"] or Decimal("0.00")) + account.opening_credit
        return (d - c).quantize(Decimal("0.01"))

    @staticmethod
    def _infer_target_kind(account: Account) -> tuple[str, str]:
        role = account.control_role
        if role in (Account.ControlRole.SUNDRY_CREDITORS, Account.ControlRole.SUBCONTRACTOR_PAYABLE):
            return AccountRelationship.TargetKind.SUPPLIER_CONTRACTOR, "INVOICE_ALLOCATION"
        if role == Account.ControlRole.SUNDRY_DEBTORS:
            return AccountRelationship.TargetKind.CUSTOMER_CLIENT, "RECEIVABLE_ALLOCATION"
        if role in (Account.ControlRole.EMPLOYEE_PAYABLE, Account.ControlRole.WAGES_PAYABLE, Account.ControlRole.EMPLOYEE_REIMBURSEMENT):
            return AccountRelationship.TargetKind.EMPLOYEE, "PAYROLL_REF"
        if role == Account.ControlRole.EMPLOYEE_ADVANCE:
            return AccountRelationship.TargetKind.EMPLOYEE_ADVANCE, "ADVANCE_REF"
        if role == Account.ControlRole.STAFF_LOAN_RECEIVABLE:
            return AccountRelationship.TargetKind.STAFF_LOAN, "LOAN_REF"
        if role == Account.ControlRole.SUPPLIER_ADVANCE:
            return AccountRelationship.TargetKind.SUPPLIER_ADVANCE, "ADVANCE_REF"
        if role == Account.ControlRole.CUSTOMER_ADVANCE:
            return AccountRelationship.TargetKind.CUSTOMER_ADVANCE, "ADVANCE_REF"
        if role == Account.ControlRole.PROJECT_WIP:
            return AccountRelationship.TargetKind.PROJECT_WIP, "PROJECT_SITE_COST_CODE"
        if role == Account.ControlRole.BANK:
            return AccountRelationship.TargetKind.BANK_ACCOUNT, "BANK_REF"
        if role == Account.ControlRole.CASH:
            return AccountRelationship.TargetKind.CASH_ACCOUNT, "CASH_CUSTODIAN"
        if role == Account.ControlRole.OFFICE_EXPENSES:
            return AccountRelationship.TargetKind.CHILD_EXPENSE, "DEPARTMENT_PROJECT"
        if role == Account.ControlRole.DIRECT_EXPENSES:
            return AccountRelationship.TargetKind.DIRECT_EXPENSE, "PROJECT_SITE_COST_CODE"
        if role == Account.ControlRole.OTHER_INCOME:
            return AccountRelationship.TargetKind.INCOME_SUB, ""
        if role == Account.ControlRole.LOSS_WRITE_OFF:
            return AccountRelationship.TargetKind.LOSS_SUB, ""

        # Fallback heuristics from parent code / name / children hierarchy
        name_l = account.name.lower()
        if account.is_group or account.children.filter(is_active=True).exists():
            if account.account_type == Account.AccountType.EXPENSE:
                if "office" in name_l or "admin" in name_l:
                    return AccountRelationship.TargetKind.CHILD_EXPENSE, "DEPARTMENT_PROJECT"
                return AccountRelationship.TargetKind.DIRECT_EXPENSE, "PROJECT_SITE_COST_CODE"
            if account.account_type == Account.AccountType.INCOME:
                return AccountRelationship.TargetKind.SALES_SUB, ""
        if account.account_type == Account.AccountType.EXPENSE:
            if "office" in name_l or "rent" in name_l or "electric" in name_l or "internet" in name_l or "stationery" in name_l:
                return AccountRelationship.TargetKind.CHILD_EXPENSE, "DEPARTMENT_PROJECT"
            return AccountRelationship.TargetKind.DIRECT_EXPENSE, "PROJECT_SITE_COST_CODE"
        if account.account_type == Account.AccountType.INCOME:
            return AccountRelationship.TargetKind.SALES_SUB, ""
        return "", ""

    @staticmethod
    def list_eligible_accounts(company, voucher_type: str = "JOURNAL") -> list[dict]:
        accounts = list(
            Account.objects.select_related("parent")
            .prefetch_related("relationships", "children")
            .filter(company=company, is_active=True)
            .order_by("code")
        )
        rows = []
        for acc in accounts:
            rel = next((r for r in acc.relationships.all() if r.is_active), None)
            if rel:
                target_kind = rel.target_kind
                extra_selector = rel.extra_selector
                suggested_counter_id = str(rel.suggested_counter_account_id) if rel.suggested_counter_account_id else None
                require_project = rel.require_project
                require_reason = rel.require_reason_on_journal
            else:
                target_kind, extra_selector = AccountIntelligenceService._infer_target_kind(acc)
                suggested_counter_id = None
                require_project = acc.control_role in (
                    Account.ControlRole.PROJECT_WIP,
                    Account.ControlRole.DIRECT_EXPENSES,
                )
                require_reason = acc.control_role in (
                    Account.ControlRole.SUNDRY_DEBTORS,
                    Account.ControlRole.SUNDRY_CREDITORS,
                )

            child_cnt = sum(1 for c in acc.children.all() if c.is_active)
            # Include parent groups when they act as expandable categories (Office Expenses, Direct Expenses, etc.)
            if not acc.allow_direct_posting and child_cnt == 0:
                continue

            bal = AccountIntelligenceService._current_gl_balance(company, acc)
            rows.append(
                {
                    "id": str(acc.id),
                    "code": acc.code,
                    "name": acc.name,
                    "account_type": acc.account_type,
                    "account_class": acc.effective_class,
                    "normal_balance": acc.normal_balance,
                    "control_role": acc.control_role,
                    "parent_id": str(acc.parent_id) if acc.parent_id else None,
                    "parent_code": acc.parent.code if acc.parent else None,
                    "parent_name": acc.parent.name if acc.parent else None,
                    "is_group": acc.is_group,
                    "child_count": child_cnt,
                    "is_control_account": acc.is_control_account,
                    "requires_subledger": acc.requires_subledger,
                    "allow_direct_posting": acc.allow_direct_posting,
                    "current_balance": str(abs(bal)),
                    "current_balance_signed": str(bal),
                    "balance_side": "Dr" if bal >= 0 else "Cr",
                    "target_kind": target_kind,
                    "extra_selector": extra_selector,
                    "suggested_counter_account": suggested_counter_id,
                    "require_project": require_project,
                    "require_reason_on_journal": require_reason,
                }
            )
        return rows

    @staticmethod
    def _build_party_summary_row(company, p: Party, today) -> dict:
        agg = PartyLedgerEntry.objects.filter(company=company, party=p).aggregate(
            d=Sum("debit"), c=Sum("credit"), ret=Sum("retention_amount"), adv=Sum("advance_adjusted")
        )
        opening_net = p.opening_debit - p.opening_credit
        period_d = agg["d"] or Decimal("0.00")
        period_c = agg["c"] or Decimal("0.00")
        net = opening_net + period_d - period_c

        overdue = Decimal("0.00")
        for e in PartyLedgerEntry.objects.filter(company=company, party=p, due_date__lt=today):
            overdue += abs(e.debit - e.credit)

        open_adv = sum(
            (a.remaining_amount for a in AdvanceRecord.objects.filter(company=company, party=p, status__in=["OPEN", "PARTIALLY_ADJUSTED"])),
            Decimal("0.00"),
        )

        # Open invoices/bills against this party
        bill_types = (
            [Voucher.VoucherType.SALES, Voucher.VoucherType.CLIENT_RA_BILL]
            if p.party_type == Party.PartyType.CUSTOMER
            else [
                Voucher.VoucherType.PURCHASE,
                Voucher.VoucherType.MATERIAL_PURCHASE,
                Voucher.VoucherType.SITE_PURCHASE,
                Voucher.VoucherType.SUBCONTRACTOR_BILL,
            ]
        )
        open_invoices = []
        for bv in Voucher.objects.filter(company=company, party=p, status=Voucher.Status.POSTED, voucher_type__in=bill_types).order_by("voucher_date"):
            bill_total = bv.net_amount if bv.net_amount > 0 else sum((l.debit for l in bv.lines.all()), Decimal("0.00"))
            alloc = BillAllocation.objects.filter(company=company, party=p, against_voucher=bv).aggregate(s=Sum("allocated_amount"))["s"] or Decimal("0.00")
            outstanding = max(Decimal("0.00"), bill_total - alloc)
            if outstanding > 0:
                open_invoices.append(
                    {
                        "voucher_id": str(bv.id),
                        "voucher_no": bv.voucher_no,
                        "voucher_type": bv.voucher_type,
                        "supplier_invoice_no": bv.supplier_invoice_no or bv.voucher_no,
                        "voucher_date": bv.voucher_date.isoformat(),
                        "bs_date": bv.bs_date,
                        "total_amount": str(bill_total),
                        "settled_amount": str(alloc),
                        "outstanding_amount": str(outstanding),
                    }
                )

        latest_entry = PartyLedgerEntry.objects.filter(company=company, party=p).order_by("-entry_date", "-created_at").first()

        return {
            "id": str(p.id),
            "code": p.code,
            "name": p.name,
            "party_type": p.party_type,
            "pan_vat_no": p.pan_vat_no,
            "phone": p.phone,
            "email": p.email,
            "credit_limit": str(p.credit_limit),
            "payment_terms_days": p.payment_terms_days,
            "project_id": str(p.project_id) if p.project_id else None,
            "project_code": p.project.code if p.project else "",
            "contract_amount": str(p.project.contract_amount) if p.project else "0.00",
            "opening_balance": str(abs(opening_net)),
            "opening_side": "Dr" if opening_net >= 0 else "Cr",
            "total_billed": str(period_c if p.party_type in ("SUPPLIER", "SUBCONTRACTOR") else period_d),
            "total_settled": str(period_d if p.party_type in ("SUPPLIER", "SUBCONTRACTOR") else period_c),
            "current_outstanding": str(abs(net)),
            "outstanding_side": "Dr" if net >= 0 else "Cr",
            "overdue_balance": str(overdue),
            "unallocated_advances": str(open_adv),
            "retention_balance": str(agg["ret"] or Decimal("0.00")),
            "latest_transaction": {
                "date": latest_entry.entry_date.isoformat(),
                "reference": latest_entry.reference_no,
                "narration": latest_entry.narration,
            } if latest_entry else None,
            "open_invoices": open_invoices,
        }

    @staticmethod
    def get_employee_financial_summary(company, emp: EmployeeProfile) -> dict:
        open_advances = list(
            AdvanceRecord.objects.select_related("source_voucher", "project", "control_account")
            .filter(company=company, employee=emp, status__in=["OPEN", "PARTIALLY_ADJUSTED"])
            .order_by("issue_date")
        )
        outstanding_adv = sum((a.remaining_amount for a in open_advances), Decimal("0.00"))
        prev_settlement = (
            AdvanceAdjustment.objects.filter(company=company, advance__employee=emp)
            .aggregate(s=Sum("adjusted_amount"))["s"]
            or Decimal("0.00")
        )
        payrolls = list(
            PayrollLiability.objects.select_related("project", "control_account")
            .filter(company=company, employee=emp, status__in=["UNPAID", "PARTIALLY_PAID"])
            .order_by("-created_at")
        )
        unpaid_wages = sum((p.outstanding_amount for p in payrolls), Decimal("0.00"))
        loans = list(
            StaffLoan.objects.select_related("control_account")
            .filter(company=company, employee=emp, status=StaffLoan.Status.ACTIVE)
        )
        loan_bal = sum((l.remaining_principal for l in loans), Decimal("0.00"))
        net_payable = unpaid_wages - outstanding_adv

        return {
            "id": str(emp.id),
            "party_id": str(emp.party_id),
            "employee_code": emp.employee_code,
            "full_name": emp.full_name,
            "department_id": str(emp.department_id) if emp.department_id else None,
            "department_name": emp.department.name if emp.department else "",
            "designation": emp.designation,
            "project_id": str(emp.project_id) if emp.project_id else None,
            "project_code": emp.project.code if emp.project else "",
            "basic_salary": str(emp.basic_salary),
            "unpaid_wages": str(unpaid_wages),
            "outstanding_advance": str(outstanding_adv),
            "previous_settlement": str(prev_settlement),
            "staff_loan_balance": str(loan_bal),
            "net_payable": str(net_payable),
            "advances": [
                {
                    "id": str(a.id),
                    "advance_no": a.advance_no,
                    "advance_type": a.advance_type,
                    "issue_date": a.issue_date.isoformat(),
                    "bs_date": a.bs_date,
                    "source_voucher_no": a.source_voucher.voucher_no if a.source_voucher else "",
                    "original_amount": str(a.original_amount),
                    "adjusted_amount": str(a.adjusted_amount),
                    "remaining_amount": str(a.remaining_amount),
                    "status": a.status,
                    "remarks": a.remarks,
                }
                for a in open_advances
            ],
            "payrolls": [
                {
                    "id": str(p.id),
                    "payroll_ref": p.payroll_ref,
                    "period_label": p.period_label,
                    "project_code": p.project.code if p.project else "",
                    "gross_wages": str(p.gross_wages),
                    "settled_amount": str(p.settled_amount),
                    "outstanding_amount": str(p.outstanding_amount),
                    "status": p.status,
                }
                for p in payrolls
            ],
            "loans": [
                {
                    "id": str(l.id),
                    "loan_no": l.loan_no,
                    "principal_amount": str(l.principal_amount),
                    "repaid_amount": str(l.repaid_amount),
                    "remaining_principal": str(l.remaining_principal),
                    "monthly_installment": str(l.monthly_installment),
                    "interest_rate_pct": str(l.interest_rate_pct),
                }
                for l in loans
            ],
        }

    @staticmethod
    def get_related_context(company, account: Account, project_id: str | None = None) -> dict:
        today = timezone.localdate()
        rel = AccountRelationship.objects.filter(company=company, account=account, is_active=True).first()
        if rel:
            target_kind = rel.target_kind
            extra_selector = rel.extra_selector
            suggested_id = str(rel.suggested_counter_account_id) if rel.suggested_counter_account_id else None
        else:
            target_kind, extra_selector = AccountIntelligenceService._infer_target_kind(account)
            suggested_id = None

        gl_bal = AccountIntelligenceService._current_gl_balance(company, account)

        related_parties = []
        child_ledgers = []
        employees = []
        advances = []
        bank_accounts = []
        cash_accounts = []

        # 1. Parties (Creditors / Debtors / Advance holders)
        if target_kind == AccountRelationship.TargetKind.SUPPLIER_CONTRACTOR:
            p_qs = Party.objects.select_related("project").filter(
                company=company, is_active=True, party_type__in=[Party.PartyType.SUPPLIER, Party.PartyType.SUBCONTRACTOR]
            )
            if account.control_role == Account.ControlRole.SUBCONTRACTOR_PAYABLE:
                p_qs = p_qs.filter(party_type=Party.PartyType.SUBCONTRACTOR)
            related_parties = [AccountIntelligenceService._build_party_summary_row(company, p, today) for p in p_qs]

        elif target_kind == AccountRelationship.TargetKind.CUSTOMER_CLIENT:
            p_qs = Party.objects.select_related("project").filter(
                company=company, is_active=True, party_type=Party.PartyType.CUSTOMER
            )
            related_parties = [AccountIntelligenceService._build_party_summary_row(company, p, today) for p in p_qs]

        elif target_kind == AccountRelationship.TargetKind.SUPPLIER_ADVANCE:
            adv_qs = AdvanceRecord.objects.select_related("party", "project", "source_voucher").filter(
                company=company,
                status__in=["OPEN", "PARTIALLY_ADJUSTED"],
                advance_type__in=[
                    AdvanceRecord.AdvanceType.SUPPLIER_ADVANCE,
                    AdvanceRecord.AdvanceType.MOBILIZATION_ADVANCE,
                ],
            )
            advances = [
                {
                    "id": str(a.id),
                    "advance_no": a.advance_no,
                    "advance_type": a.advance_type,
                    "party_id": str(a.party_id),
                    "party_name": a.party.name,
                    "issue_date": a.issue_date.isoformat(),
                    "original_amount": str(a.original_amount),
                    "adjusted_amount": str(a.adjusted_amount),
                    "remaining_amount": str(a.remaining_amount),
                    "source_voucher_no": a.source_voucher.voucher_no if a.source_voucher else "",
                }
                for a in adv_qs
            ]
            p_ids = {a.party_id for a in adv_qs}
            for p in Party.objects.select_related("project").filter(id__in=p_ids, is_active=True):
                related_parties.append(AccountIntelligenceService._build_party_summary_row(company, p, today))

        elif target_kind == AccountRelationship.TargetKind.CUSTOMER_ADVANCE:
            adv_qs = AdvanceRecord.objects.select_related("party", "project", "source_voucher").filter(
                company=company,
                status__in=["OPEN", "PARTIALLY_ADJUSTED"],
                advance_type=AdvanceRecord.AdvanceType.CUSTOMER_ADVANCE,
            )
            advances = [
                {
                    "id": str(a.id),
                    "advance_no": a.advance_no,
                    "advance_type": a.advance_type,
                    "party_id": str(a.party_id),
                    "party_name": a.party.name,
                    "issue_date": a.issue_date.isoformat(),
                    "original_amount": str(a.original_amount),
                    "adjusted_amount": str(a.adjusted_amount),
                    "remaining_amount": str(a.remaining_amount),
                    "source_voucher_no": a.source_voucher.voucher_no if a.source_voucher else "",
                }
                for a in adv_qs
            ]
            p_ids = {a.party_id for a in adv_qs}
            for p in Party.objects.select_related("project").filter(id__in=p_ids, is_active=True):
                related_parties.append(AccountIntelligenceService._build_party_summary_row(company, p, today))

        # 2. Employees / Wages / Staff Advances / Staff Loans
        elif target_kind in (
            AccountRelationship.TargetKind.EMPLOYEE,
            AccountRelationship.TargetKind.EMPLOYEE_ADVANCE,
            AccountRelationship.TargetKind.STAFF_LOAN,
        ):
            emp_qs = EmployeeProfile.objects.select_related("party", "department", "project").filter(
                company=company, is_active=True
            )
            for emp in emp_qs:
                summary = AccountIntelligenceService.get_employee_financial_summary(company, emp)
                if target_kind == AccountRelationship.TargetKind.EMPLOYEE_ADVANCE and Decimal(summary["outstanding_advance"]) <= 0:
                    continue
                if target_kind == AccountRelationship.TargetKind.STAFF_LOAN and Decimal(summary["staff_loan_balance"]) <= 0:
                    continue
                employees.append(summary)
                for a in summary["advances"]:
                    advances.append({**a, "party_id": str(emp.party_id), "party_name": emp.full_name, "employee_id": str(emp.id)})

        # 3. Child Ledgers (Office Expenses, Direct Expenses, Purchase, Sales, Income, Losses, Groups)
        children_qs = Account.objects.filter(company=company, parent=account, is_active=True).order_by("code")
        for ch in children_qs:
            cbal = AccountIntelligenceService._current_gl_balance(company, ch)
            child_ledgers.append(
                {
                    "id": str(ch.id),
                    "code": ch.code,
                    "name": ch.name,
                    "account_type": ch.account_type,
                    "account_class": ch.effective_class,
                    "normal_balance": ch.normal_balance,
                    "control_role": ch.control_role,
                    "current_balance": str(abs(cbal)),
                    "balance_side": "Dr" if cbal >= 0 else "Cr",
                }
            )
        if not child_ledgers and account.parent_id and account.account_type == Account.AccountType.EXPENSE:
            for sib in Account.objects.filter(company=company, parent_id=account.parent_id, is_active=True, is_group=False).order_by("code"):
                sbal = AccountIntelligenceService._current_gl_balance(company, sib)
                child_ledgers.append(
                    {
                        "id": str(sib.id),
                        "code": sib.code,
                        "name": sib.name,
                        "account_type": sib.account_type,
                        "account_class": sib.effective_class,
                        "normal_balance": sib.normal_balance,
                        "control_role": sib.control_role,
                        "current_balance": str(abs(sbal)),
                        "balance_side": "Dr" if sbal >= 0 else "Cr",
                    }
                )

        # 4. Bank & Cash registers
        if target_kind == AccountRelationship.TargetKind.BANK_ACCOUNT:
            for ba in BankAccount.objects.select_related("bank_branch__bank", "gl_account", "project").filter(
                company=company, status=BankAccount.Status.ACTIVE
            ):
                bbal = AccountIntelligenceService._current_gl_balance(company, ba.gl_account) if ba.gl_account else Decimal("0.00")
                bank_accounts.append(
                    {
                        "id": str(ba.id),
                        "account_name": ba.account_name,
                        "bank_name": ba.bank_branch.bank.name,
                        "account_number_masked": ba.account_number_masked,
                        "currency": ba.currency,
                        "gl_account_id": str(ba.gl_account_id) if ba.gl_account_id else None,
                        "gl_balance": str(bbal),
                    }
                )
        elif target_kind == AccountRelationship.TargetKind.CASH_ACCOUNT:
            for ca in CashAccount.objects.select_related("gl_account", "project", "custodian").filter(
                company=company, is_active=True
            ):
                cbal = AccountIntelligenceService._current_gl_balance(company, ca.gl_account) if ca.gl_account else Decimal("0.00")
                cash_accounts.append(
                    {
                        "id": str(ca.id),
                        "name": ca.name,
                        "cash_type": ca.cash_type,
                        "custodian": ca.custodian.username if ca.custodian else "",
                        "gl_account_id": str(ca.gl_account_id) if ca.gl_account_id else None,
                        "gl_balance": str(cbal),
                    }
                )

        # 5. Recent ledger transactions on this account
        recent_txns = [
            {
                "id": str(le.id),
                "posting_date": le.posting_date.isoformat(),
                "bs_date": le.bs_date,
                "voucher_no": le.voucher.voucher_no if le.voucher else "",
                "voucher_type": le.voucher.voucher_type if le.voucher else "",
                "party_name": le.party.name if le.party else "",
                "project_code": le.project.code if le.project else "",
                "debit": str(le.base_debit),
                "credit": str(le.base_credit),
                "narration": le.narration,
            }
            for le in LedgerEntry.objects.select_related("voucher", "party", "project")
            .filter(company=company, account=account)
            .order_by("-posting_date", "-posted_at")[:8]
        ]

        # 6. Counter-account suggestions
        suggested_counters = []
        if suggested_id:
            sc = Account.objects.filter(id=suggested_id, company=company, is_active=True).first()
            if sc:
                suggested_counters.append({"id": str(sc.id), "code": sc.code, "name": sc.name, "reason": "Configured policy counter-account"})
        if account.account_type == Account.AccountType.EXPENSE:
            for role, reason in [
                (Account.ControlRole.OUTSTANDING_EXPENSES, "Accrue unpaid expense to Outstanding Expenses A/C"),
                (Account.ControlRole.SUNDRY_CREDITORS, "Book accrued payable against Supplier / Contractor"),
                (Account.ControlRole.EMPLOYEE_ADVANCE, "Settle employee advance against verified project expense bills"),
                (Account.ControlRole.CASH, "Direct petty/site cash settlement"),
            ]:
                cand = Account.objects.filter(company=company, control_role=role, is_group=False, is_active=True).first()
                if cand and all(x["id"] != str(cand.id) for x in suggested_counters):
                    suggested_counters.append({"id": str(cand.id), "code": cand.code, "name": cand.name, "reason": reason})
        elif account.control_role in (Account.ControlRole.WAGES_PAYABLE, Account.ControlRole.EMPLOYEE_PAYABLE):
            adv_acc = Account.objects.filter(company=company, control_role=Account.ControlRole.EMPLOYEE_ADVANCE, is_group=False, is_active=True).first()
            if adv_acc:
                suggested_counters.append({"id": str(adv_acc.id), "code": adv_acc.code, "name": adv_acc.name, "reason": "Recover outstanding Employee Advance against Wages Payable"})
        elif account.control_role == Account.ControlRole.EMPLOYEE_ADVANCE:
            for role, reason in [
                (Account.ControlRole.WAGES_PAYABLE, "Deduct Staff Advance from unpaid Wages Payable"),
                (Account.ControlRole.DIRECT_EXPENSES, "Settle Staff Advance against verified Project Expense"),
                (Account.ControlRole.CASH, "Receive unused advance cash back to Cash A/C"),
            ]:
                cand = Account.objects.filter(company=company, control_role=role, is_group=False, is_active=True).first()
                if cand:
                    suggested_counters.append({"id": str(cand.id), "code": cand.code, "name": cand.name, "reason": reason})

        return {
            "account": {
                "id": str(account.id),
                "code": account.code,
                "name": account.name,
                "account_type": account.account_type,
                "account_class": account.effective_class,
                "normal_balance": account.normal_balance,
                "control_role": account.control_role,
                "parent_label": f"{account.parent.code} — {account.parent.name}" if account.parent else "Root Group",
                "is_group": account.is_group,
                "current_balance": str(abs(gl_bal)),
                "balance_side": "Dr" if gl_bal >= 0 else "Cr",
            },
            "relationship": {
                "target_kind": target_kind,
                "extra_selector": extra_selector,
                "require_project": rel.require_project if rel else (account.control_role in (Account.ControlRole.PROJECT_WIP, Account.ControlRole.DIRECT_EXPENSES)),
                "require_reason_on_journal": rel.require_reason_on_journal if rel else (account.control_role in (Account.ControlRole.SUNDRY_DEBTORS, Account.ControlRole.SUNDRY_CREDITORS)),
                "notes": rel.notes if rel else "",
            },
            "related_parties": related_parties,
            "child_ledgers": child_ledgers,
            "employees": employees,
            "advances": advances,
            "bank_accounts": bank_accounts,
            "cash_accounts": cash_accounts,
            "recent_transactions": recent_txns,
            "suggested_counter_accounts": suggested_counters,
        }


class AdvanceAdjustmentService:
    """Validates, previews, and atomically settles outstanding advances, payroll liabilities, and staff loans."""

    @staticmethod
    def list_eligible_advances(company, party_id: str | None = None, employee_id: str | None = None, advance_type: str | None = None) -> list[dict]:
        qs = AdvanceRecord.objects.select_related("party", "employee", "project", "control_account", "source_voucher").filter(
            company=company, status__in=[AdvanceRecord.Status.OPEN, AdvanceRecord.Status.PARTIALLY_ADJUSTED]
        )
        if party_id:
            qs = qs.filter(party_id=party_id)
        if employee_id:
            qs = qs.filter(employee_id=employee_id)
        if advance_type:
            qs = qs.filter(advance_type=advance_type)

        rows = []
        for a in qs:
            if a.remaining_amount <= 0:
                continue
            rows.append(
                {
                    "id": str(a.id),
                    "advance_no": a.advance_no,
                    "advance_type": a.advance_type,
                    "party_id": str(a.party_id),
                    "party_name": a.party.name,
                    "employee_id": str(a.employee_id) if a.employee_id else None,
                    "employee_code": a.employee.employee_code if a.employee else "",
                    "project_code": a.project.code if a.project else "",
                    "control_account_id": str(a.control_account_id),
                    "control_account_label": f"{a.control_account.code} — {a.control_account.name}",
                    "source_voucher_no": a.source_voucher.voucher_no if a.source_voucher else "",
                    "issue_date": a.issue_date.isoformat(),
                    "bs_date": a.bs_date,
                    "original_amount": str(a.original_amount),
                    "adjusted_amount": str(a.adjusted_amount),
                    "remaining_amount": str(a.remaining_amount),
                    "status": a.status,
                    "remarks": a.remarks,
                }
            )
        return rows

    @staticmethod
    def preview_adjustment(*, company, advance: AdvanceRecord, current_adjustment: Decimal) -> dict:
        orig = advance.original_amount
        prev = advance.adjusted_amount
        rem_before = advance.remaining_amount
        curr = Decimal(str(current_adjustment or "0.00")).quantize(Decimal("0.01"))
        rem_after = rem_before - curr
        errors = []
        if advance.company_id != company.id:
            errors.append("Advance belongs to another company.")
        if advance.status in (AdvanceRecord.Status.SETTLED, AdvanceRecord.Status.CANCELLED) or rem_before <= 0:
            errors.append(f"Advance {advance.advance_no} is already closed/settled.")
        if curr <= 0:
            errors.append("Adjustment amount must be greater than zero.")
        if curr > rem_before:
            errors.append(f"Adjustment ({curr}) exceeds remaining advance balance ({rem_before}).")
        return {
            "advance_id": str(advance.id),
            "advance_no": advance.advance_no,
            "party_name": advance.party.name,
            "original_amount": str(orig),
            "previously_adjusted": str(prev),
            "remaining_before": str(rem_before),
            "current_adjustment": str(curr),
            "remaining_after": str(max(Decimal("0.00"), rem_after)),
            "is_valid": len(errors) == 0,
            "validation_errors": errors,
        }

    @staticmethod
    def get_adjustment_history(company, advance: AdvanceRecord) -> dict:
        adjs = AdvanceAdjustment.objects.select_related("voucher", "adjusted_by").filter(
            company=company, advance=advance
        )
        return {
            "advance": {
                "id": str(advance.id),
                "advance_no": advance.advance_no,
                "party_name": advance.party.name,
                "original_amount": str(advance.original_amount),
                "adjusted_amount": str(advance.adjusted_amount),
                "remaining_amount": str(advance.remaining_amount),
                "status": advance.status,
            },
            "history": [
                {
                    "id": str(x.id),
                    "voucher_id": str(x.voucher_id),
                    "voucher_no": x.voucher.voucher_no,
                    "voucher_date": x.voucher.voucher_date.isoformat(),
                    "adjusted_amount": str(x.adjusted_amount),
                    "supporting_bill_ref": x.supporting_bill_ref,
                    "notes": x.notes,
                    "adjusted_by": x.adjusted_by.username,
                    "adjusted_at": x.adjusted_at.isoformat(),
                }
                for x in adjs
            ],
        }

    @staticmethod
    def apply_voucher_references_on_post(*, voucher: Voucher, user) -> None:
        """Called inside PostingService.post_voucher() transaction.atomic() block with row locks."""
        lines = list(voucher.lines.select_related("account", "party", "advance_record", "payroll_liability", "staff_loan", "against_voucher"))

        for line in lines:
            amt = line.debit if line.debit > 0 else line.credit
            line_party = line.party or voucher.party

            # 1. Settle AdvanceRecord when linked on line
            if line.advance_record_id:
                adv = AdvanceRecord.objects.select_for_update().get(pk=line.advance_record_id, company=voucher.company)
                if AdvanceAdjustment.objects.filter(advance=adv, voucher=voucher).exists():
                    raise ValidationError(f"Duplicate simultaneous advance adjustment detected for {adv.advance_no}.")
                if amt > adv.remaining_amount:
                    raise ValidationError(
                        f"Adjustment {amt} exceeds remaining balance ({adv.remaining_amount}) on advance {adv.advance_no}."
                    )
                AdvanceAdjustment.objects.create(
                    company=voucher.company,
                    advance=adv,
                    voucher=voucher,
                    adjusted_amount=amt,
                    supporting_bill_ref=voucher.supplier_invoice_no or voucher.reference_no or "",
                    notes=line.description or voucher.narration[:255],
                    adjusted_by=user,
                )
                adv.adjusted_amount += amt
                adv.status = (
                    AdvanceRecord.Status.SETTLED
                    if adv.remaining_amount <= Decimal("0.00")
                    else AdvanceRecord.Status.PARTIALLY_ADJUSTED
                )
                adv.save(update_fields=["adjusted_amount", "status"])

            # 2. Settle PayrollLiability when linked on line
            if line.payroll_liability_id:
                pr = PayrollLiability.objects.select_for_update().get(pk=line.payroll_liability_id, company=voucher.company)
                if amt > pr.outstanding_amount:
                    raise ValidationError(
                        f"Amount {amt} exceeds unpaid payroll liability ({pr.outstanding_amount}) on {pr.payroll_ref}."
                    )
                pr.settled_amount += amt
                pr.status = (
                    PayrollLiability.Status.SETTLED
                    if pr.outstanding_amount <= Decimal("0.00")
                    else PayrollLiability.Status.PARTIALLY_PAID
                )
                pr.save(update_fields=["settled_amount", "status"])

            # 3. Repay StaffLoan installment when linked on line
            if line.staff_loan_id:
                loan = StaffLoan.objects.select_for_update().get(pk=line.staff_loan_id, company=voucher.company)
                if amt > loan.remaining_principal:
                    raise ValidationError(
                        f"Repayment {amt} exceeds remaining loan principal ({loan.remaining_principal}) on {loan.loan_no}."
                    )
                loan.repaid_amount += amt
                if loan.remaining_installments > 0:
                    loan.remaining_installments -= 1
                loan.status = (
                    StaffLoan.Status.SETTLED
                    if loan.remaining_principal <= Decimal("0.00")
                    else StaffLoan.Status.ACTIVE
                )
                loan.save(update_fields=["repaid_amount", "remaining_installments", "status"])

            # 4. Invoice allocation (BillAllocation) when against_voucher is linked
            if line.against_voucher_id and line_party:
                if not BillAllocation.objects.filter(settlement_voucher=voucher, against_voucher_id=line.against_voucher_id).exists():
                    BillAllocation.objects.create(
                        company=voucher.company,
                        party=line_party,
                        settlement_voucher=voucher,
                        against_voucher_id=line.against_voucher_id,
                        allocated_amount=amt,
                    )

        # 5. Also create AdvanceRecord when posting a new Advance disbursement voucher
        if voucher.voucher_type in (Voucher.VoucherType.STAFF_ADVANCE, Voucher.VoucherType.MOBILIZATION_ADVANCE):
            for line in lines:
                line_party = line.party or voucher.party
                if line_party and not line.advance_record_id and line.account.control_role in (
                    Account.ControlRole.EMPLOYEE_ADVANCE,
                    Account.ControlRole.SUPPLIER_ADVANCE,
                    Account.ControlRole.CUSTOMER_ADVANCE,
                ):
                    amt = line.debit if line.debit > 0 else line.credit
                    if amt > 0:
                        adv_no = f"ADV-{voucher.voucher_no}"
                        if not AdvanceRecord.objects.filter(company=voucher.company, advance_no=adv_no).exists():
                            emp = getattr(line_party, "employee_profile", None)
                            adv_type = (
                                AdvanceRecord.AdvanceType.EMPLOYEE_ADVANCE
                                if line.account.control_role == Account.ControlRole.EMPLOYEE_ADVANCE
                                else AdvanceRecord.AdvanceType.CUSTOMER_ADVANCE
                                if line.account.control_role == Account.ControlRole.CUSTOMER_ADVANCE
                                else AdvanceRecord.AdvanceType.MOBILIZATION_ADVANCE
                                if voucher.voucher_type == Voucher.VoucherType.MOBILIZATION_ADVANCE
                                else AdvanceRecord.AdvanceType.SUPPLIER_ADVANCE
                            )
                            AdvanceRecord.objects.create(
                                company=voucher.company,
                                advance_no=adv_no[:40],
                                advance_type=adv_type,
                                party=line_party,
                                employee=emp,
                                project=line.project or voucher.project,
                                control_account=line.account,
                                source_voucher=voucher,
                                issue_date=voucher.voucher_date,
                                bs_date=voucher.bs_date or ad_to_bs(voucher.voucher_date).isoformat(),
                                original_amount=amt,
                                remarks=line.description or voucher.narration[:255],
                            )

