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

from apps.accounts_rbac.models import CompanyMembership
from apps.accounts_rbac.policies import check_approval_authority
from apps.audit.services import record_audit_event
from apps.dashboard.cache import bump_dashboard_cache
from apps.localization.bs_calendar import ad_to_bs
from apps.tenancy.models import FiscalPeriod, FiscalYear
from apps.accounting.models import (
    Account,
    CostCategory,
    CostCenter,
    LedgerEntry,
    Party,
    PartyLedgerEntry,
    Voucher,
    VoucherApprovalStep,
    VoucherLine,
    VoucherLineCostAllocation,
    VoucherLineInventoryItem,
    VoucherLogicSnapshot,
    VoucherRevision,
    VoucherSequence,
)
from .journal_intelligence import AdvanceAdjustmentService
from .posting_engine import PostingRuleEngine
from .tally_config_service import TallyConfigService

VOUCHER_PREFIX = {
    Voucher.VoucherType.JOURNAL: "JV",
    Voucher.VoucherType.PAYMENT: "PV",
    Voucher.VoucherType.RECEIPT: "RV",
    Voucher.VoucherType.CONTRA: "CV",
    Voucher.VoucherType.PURCHASE: "PU",
    Voucher.VoucherType.SALES: "SV",
    Voucher.VoucherType.CREDIT_NOTE: "CN",
    Voucher.VoucherType.DEBIT_NOTE: "DN",
    Voucher.VoucherType.REVERSING_JOURNAL: "RJV",
    Voucher.VoucherType.OPTIONAL: "OPT",
    Voucher.VoucherType.POST_DATED: "PDC",
    Voucher.VoucherType.MEMORANDUM: "MEM",
    Voucher.VoucherType.REVERSAL: "REV",
    Voucher.VoucherType.MATERIAL_PURCHASE: "MPV",
    Voucher.VoucherType.SITE_PURCHASE: "SPV",
    Voucher.VoucherType.SUBCONTRACTOR_BILL: "SCB",
    Voucher.VoucherType.CLIENT_RA_BILL: "RAB",
    Voucher.VoucherType.MOBILIZATION_ADVANCE: "MAV",
    Voucher.VoucherType.MATERIAL_CONSUMPTION: "MCV",
    Voucher.VoucherType.LABOR_PAYMENT: "LPV",
    Voucher.VoucherType.EQUIPMENT_HIRE: "EHV",
    Voucher.VoucherType.MACHINE_INCOME: "MIV",
    Voucher.VoucherType.DIRECT_EXPENSE: "DEV",
    Voucher.VoucherType.INDIRECT_EXPENSE: "IEV",
    Voucher.VoucherType.OPENING_BALANCE: "OBV",
    Voucher.VoucherType.DEPRECIATION: "DEP",
    Voucher.VoucherType.FX_ADJUSTMENT: "FXV",
}


def resolve_fiscal_context(company, voucher_date: date) -> tuple[FiscalYear, FiscalPeriod]:
    period = (
        FiscalPeriod.objects.select_related("fiscal_year")
        .filter(
            fiscal_year__company=company,
            start_date__lte=voucher_date,
            end_date__gte=voucher_date,
        )
        .first()
    )
    if not period:
        raise ValidationError(
            f"No configured fiscal period covers {voucher_date.isoformat()} for {company.code}."
        )
    if period.fiscal_year.is_closed or period.status != FiscalPeriod.Status.OPEN:
        raise ValidationError(
            f"Fiscal period '{period.name}' is {period.status}; transactions cannot be posted."
        )
    return period.fiscal_year, period


def _validate_voucher_lines(voucher: Voucher, lines_qs) -> tuple[Decimal, Decimal]:
    lines = list(lines_qs)
    plan = PostingRuleEngine.build_voucher_accounting_plan(
        company=voucher.company,
        voucher_type=voucher.voucher_type,
        voucher_date=voucher.voucher_date,
        lines_data=[
            {
                "account": l.account,
                "debit": l.debit,
                "credit": l.credit,
                "party": l.party,
                "project": l.project or voucher.project,
                "advance_record": l.advance_record,
                "payroll_liability": l.payroll_liability,
                "staff_loan": l.staff_loan,
                "cost_allocations": [
                    {
                        "allocation_mode": ca.allocation_mode,
                        "percentage": ca.percentage,
                        "amount": ca.amount,
                    }
                    for ca in l.cost_allocations.all()
                ],
            }
            for l in lines
        ],
        party=voucher.party,
        supplier_invoice_no=voucher.supplier_invoice_no,
        is_control_override=voucher.is_control_override,
        voucher_id=voucher.id,
        voucher_type_config=voucher.voucher_type_config,
    )
    if not plan["is_valid"]:
        raise ValidationError(plan["validation_errors"])
    return Decimal(plan["total_debit"]), Decimal(plan["total_credit"])


class VoucherService:
    @staticmethod
    @transaction.atomic
    def create_draft(*, company, user, data: dict, lines_data: list[dict], device_id: str = "") -> Voucher:
        from apps.localization.services import CalendarValidationService

        voucher_date = data["voucher_date"]
        if data.get("bs_date"):
            CalendarValidationService.validate_and_resolve(
                ad_date=voucher_date,
                bs_date=data["bs_date"],
                input_calendar=data.get("input_calendar") or "BOTH",
            )
        fy, period = resolve_fiscal_context(company, voucher_date)

        idem = data.get("idempotency_key")
        if idem:
            existing = Voucher.objects.filter(company=company, idempotency_key=idem).first()
            if existing:
                return existing

        party = data.get("party")
        vtype = data["voucher_type"]
        vcfg = data.get("voucher_type_config")
        vclass = data.get("voucher_class")
        entry_mode = data.get("entry_mode") or (vcfg.default_entry_mode if vcfg else Voucher.EntryMode.DOUBLE_ENTRY)
        single_acc = data.get("single_entry_account")
        inv_items_payload = data.get("inventory_items") or []

        resolved_lines = lines_data
        if not resolved_lines and data.get("scenario"):
            resolved_lines = PostingRuleEngine.derive_scenario_lines(
                company=company,
                voucher_type=vtype,
                scenario=data["scenario"],
                party=party,
                project=data.get("project"),
                site=data.get("site"),
            )
        elif entry_mode in (Voucher.EntryMode.SINGLE_ENTRY, Voucher.EntryMode.ITEM_INVOICE) and (resolved_lines or inv_items_payload):
            # Only expand if lines are not already balanced double-entry rows
            already_balanced = bool(
                resolved_lines
                and len(resolved_lines) >= 2
                and sum((Decimal(str(r.get("debit") or "0.00")) for r in resolved_lines), Decimal("0.00")) > 0
                and sum((Decimal(str(r.get("debit") or "0.00")) for r in resolved_lines), Decimal("0.00"))
                == sum((Decimal(str(r.get("credit") or "0.00")) for r in resolved_lines), Decimal("0.00"))
            )
            if not already_balanced:
                resolved_lines = TallyConfigService.resolve_mode_and_class_lines(
                    company=company,
                    voucher_type=vtype,
                    entry_mode=entry_mode,
                    single_entry_account=single_acc,
                    voucher_class=vclass,
                    party=party,
                    lines_payload=resolved_lines,
                    inventory_items_payload=inv_items_payload,
                    project=data.get("project"),
                    site=data.get("site"),
                )

        prov_kind = data.get("provisional_kind") or (
            Voucher.ProvisionalKind.OPTIONAL
            if vtype == Voucher.VoucherType.OPTIONAL or (vcfg and vcfg.default_status == "OPTIONAL")
            else Voucher.ProvisionalKind.MEMORANDUM
            if vtype == Voucher.VoucherType.MEMORANDUM or (vcfg and vcfg.default_status == "MEMORANDUM")
            else Voucher.ProvisionalKind.POST_DATED
            if vtype == Voucher.VoucherType.POST_DATED or (vcfg and vcfg.default_status == "POST_DATED")
            else Voucher.ProvisionalKind.REVERSING_JOURNAL
            if vtype == Voucher.VoucherType.REVERSING_JOURNAL
            else Voucher.ProvisionalKind.REGULAR
        )
        initial_status = (
            Voucher.Status.OPTIONAL
            if prov_kind == Voucher.ProvisionalKind.OPTIONAL
            else Voucher.Status.MEMORANDUM
            if prov_kind == Voucher.ProvisionalKind.MEMORANDUM
            else Voucher.Status.POST_DATED
            if prov_kind == Voucher.ProvisionalKind.POST_DATED
            else Voucher.Status.DRAFT
        )

        voucher = Voucher.objects.create(
            company=company,
            branch=data.get("branch"),
            fiscal_year=fy,
            fiscal_period=period,
            voucher_no=data.get("voucher_no") or None,
            voucher_type=vtype,
            voucher_type_config=vcfg,
            voucher_class=vclass,
            entry_mode=entry_mode,
            provisional_kind=prov_kind,
            effective_date=data.get("effective_date"),
            reverse_on_date=data.get("reverse_on_date"),
            converted_from=data.get("converted_from"),
            single_entry_account=single_acc,
            bill_wise_allocations_payload=data.get("bill_wise_allocations") or [],
            voucher_date=voucher_date,
            bs_date=ad_to_bs(voucher_date).isoformat(),
            due_date=data.get("due_date"),
            currency=data.get("currency", company.base_currency),
            exchange_rate=data.get("exchange_rate", Decimal("1.000000")),
            project=data.get("project"),
            site=data.get("site"),
            department=data.get("department"),
            cost_center=data.get("cost_center"),
            party=party,
            party_name=data.get("party_name", party.name if party else ""),
            party_pan=data.get("party_pan", party.pan_vat_no if party else ""),
            supplier_invoice_no=data.get("supplier_invoice_no", ""),
            supplier_invoice_date=data.get("supplier_invoice_date"),
            reference_no=data.get("reference_no", ""),
            narration=data.get("narration", ""),
            gross_amount=Decimal(str(data.get("gross_amount") or "0.00")),
            discount_amount=Decimal(str(data.get("discount_amount") or "0.00")),
            tax_amount=Decimal(str(data.get("tax_amount") or "0.00")),
            tds_amount=Decimal(str(data.get("tds_amount") or "0.00")),
            retention_amount=Decimal(str(data.get("retention_amount") or "0.00")),
            advance_recovery_amount=Decimal(str(data.get("advance_recovery_amount") or "0.00")),
            net_amount=Decimal(str(data.get("net_amount") or "0.00")),
            theme_code=data.get("theme_code", "TALLY_CLASSIC"),
            is_control_override=bool(data.get("is_control_override", False)),
            override_reason=data.get("override_reason", ""),
            operational_payload=data.get("operational_payload") or {},
            idempotency_key=idem,
            created_by=user,
            status=initial_status,
        )

        for idx, line in enumerate(resolved_lines, start=1):
            vl = VoucherLine.objects.create(
                voucher=voucher,
                line_no=idx,
                account=line["account"],
                party=line.get("party") or party,
                debit=line.get("debit", Decimal("0.00")),
                credit=line.get("credit", Decimal("0.00")),
                bill_ref=line.get("bill_ref", ""),
                due_date=line.get("due_date"),
                project=line.get("project") or voucher.project,
                site=line.get("site") or voucher.site,
                department=line.get("department") or voucher.department,
                cost_center=line.get("cost_center") or voucher.cost_center,
                cost_code=line.get("cost_code"),
                boq_item=line.get("boq_item"),
                work_package=line.get("work_package"),
                work_activity=line.get("work_activity", ""),
                contractor=line.get("contractor"),
                equipment=line.get("equipment"),
                employee_ref=line.get("employee_ref", ""),
                against_voucher=line.get("against_voucher"),
                advance_record=line.get("advance_record"),
                payroll_liability=line.get("payroll_liability"),
                staff_loan=line.get("staff_loan"),
                expense_scope=line.get("expense_scope", ""),
                quantity=line.get("quantity", Decimal("0.000")),
                unit=line.get("unit", ""),
                unit_rate=line.get("unit_rate", Decimal("0.00")),
                tax_rate=line.get("tax_rate", Decimal("0.00")),
                tds_rate=line.get("tds_rate", Decimal("0.00")),
                retention_pct=line.get("retention_pct", Decimal("0.00")),
                is_auto_generated=bool(line.get("is_auto_generated", False)),
                description=line.get("description", ""),
            )
            splits = line.get("cost_allocations") or []
            if splits:
                line_total = max(vl.debit, vl.credit)
                split_amt_sum = Decimal("0.00")
                pct_sum = Decimal("0.00")
                has_pct = False
                for split in splits:
                    cc_raw = split.get("cost_center")
                    cc_obj = cc_raw if isinstance(cc_raw, CostCenter) else CostCenter.objects.filter(id=cc_raw, company=company).first()
                    if not cc_obj:
                        raise ValidationError("Invalid Cost Centre in cost allocation split.")
                    cat_raw = split.get("cost_category")
                    cat_obj = None
                    if cat_raw:
                        cat_obj = cat_raw if isinstance(cat_raw, CostCategory) else CostCategory.objects.filter(id=cat_raw, company=company).first()
                    mode = split.get("allocation_mode", VoucherLineCostAllocation.AllocationMode.PERCENTAGE)
                    pct = Decimal(str(split.get("percentage") or "0.00"))
                    amt = Decimal(str(split.get("amount") or "0.00"))
                    if mode == VoucherLineCostAllocation.AllocationMode.PERCENTAGE:
                        has_pct = True
                        pct_sum += pct
                        if amt <= 0 and line_total > 0:
                            amt = (line_total * pct / Decimal("100")).quantize(Decimal("0.01"))
                    split_amt_sum += amt
                    VoucherLineCostAllocation.objects.create(
                        voucher_line=vl,
                        cost_category=cat_obj,
                        cost_center=cc_obj,
                        project=split.get("project") or vl.project,
                        site=split.get("site") or vl.site,
                        cost_code=split.get("cost_code") or vl.cost_code,
                        boq_item=split.get("boq_item") or vl.boq_item,
                        allocation_mode=mode,
                        percentage=pct,
                        amount=amt,
                    )
                if has_pct and abs(pct_sum - Decimal("100.00")) > Decimal("0.05"):
                    raise ValidationError(f"Cost allocation percentages must sum to 100.00% (got {pct_sum}%).")
                if abs(split_amt_sum - line_total) > Decimal("0.05"):
                    raise ValidationError(f"Cost allocation amounts ({split_amt_sum}) must equal line total ({line_total}).")

        if inv_items_payload:
            from apps.inventory.models import ItemMaster, Warehouse
            for inv_row in inv_items_payload:
                item_obj = inv_row.get("item")
                if not item_obj and inv_row.get("item_id"):
                    item_obj = ItemMaster.objects.get(id=inv_row["item_id"], company=company)
                wh_obj = inv_row.get("warehouse")
                if not wh_obj and inv_row.get("warehouse_id"):
                    wh_obj = Warehouse.objects.filter(id=inv_row["warehouse_id"], company=company).first()
                twh_obj = inv_row.get("target_warehouse")
                if not twh_obj and inv_row.get("target_warehouse_id"):
                    twh_obj = Warehouse.objects.filter(id=inv_row["target_warehouse_id"], company=company).first()
                qty = Decimal(str(inv_row.get("quantity") or "0.000"))
                rate = Decimal(str(inv_row.get("rate") or "0.00"))
                disc = Decimal(str(inv_row.get("discount_pct") or "0.00"))
                amt = (qty * rate * (Decimal("1") - disc / Decimal("100"))).quantize(Decimal("0.01"))
                VoucherLineInventoryItem.objects.create(
                    voucher=voucher,
                    item=item_obj,
                    warehouse=wh_obj,
                    target_warehouse=twh_obj,
                    quantity=qty,
                    unit=inv_row.get("unit") or (item_obj.primary_unit.code if hasattr(item_obj, "primary_unit") and item_obj.primary_unit else ""),
                    rate=rate,
                    discount_pct=disc,
                    tax_rate=Decimal(str(inv_row.get("tax_rate") or "0.00")),
                    amount=amt,
                )

        # Enforce Contra restrictions & reserve cheque leaf when payment/contra specifies CHEQUE
        op_payload = voucher.operational_payload or {}
        if vtype == Voucher.VoucherType.CONTRA:
            from apps.banking.models import BankAccount, CashAccount

            if voucher.party_id or voucher.bill_wise_allocations_payload:
                raise ValidationError(
                    "Contra vouchers cannot include customer/supplier parties or invoice allocations."
                )
            for l in voucher.lines.select_related("account").all():
                is_treasury_acc = (
                    l.account.control_role in (Account.ControlRole.CASH, Account.ControlRole.BANK)
                    or l.account.code in ("1035", "1036", "1037")
                    or CashAccount.objects.filter(gl_account=l.account).exists()
                    or BankAccount.objects.filter(gl_account=l.account).exists()
                )
                if not is_treasury_acc:
                    raise ValidationError(
                        f"Contra vouchers may only use company Cash/Bank/In-Transit accounts (invalid: {l.account.code} {l.account.name})."
                    )
            line_accs = list(voucher.lines.values_list("account_id", flat=True))
            if len(line_accs) >= 2 and len(set(line_accs)) < 2:
                raise ValidationError("Contra source and destination accounts must be different.")

        if str(op_payload.get("payment_mode") or "").upper() == "CHEQUE" and vtype in (
            "PAYMENT",
            "CONTRA",
            "SUBCONTRACTOR_PAYMENT",
            "LABOR_PAYMENT",
            "SUPPLIER_ADVANCE",
        ):
            from apps.banking.bank_txn_services import ChequeReservationService
            from apps.banking.models import BankAccount

            leaf_id = op_payload.get("cheque_leaf_id") or op_payload.get("cheque_leaf")
            ba_id = op_payload.get("source_bank_account_id") or op_payload.get("bank_account_id")
            if not ba_id:
                raise ValidationError("Bank Account is mandatory when Payment Mode is Cheque.")
            ba_obj = BankAccount.objects.filter(id=ba_id, company=company).first()
            if not ba_obj:
                raise ValidationError("Selected Bank Account does not exist for this company.")
            if not leaf_id:
                raise ValidationError(
                    "Cheque payment requires selecting an available cheque leaf from the selected bank account."
                )
            chq_dt_raw = op_payload.get("cheque_date") or op_payload.get("instrument_date")
            chq_dt = date.fromisoformat(str(chq_dt_raw)[:10]) if chq_dt_raw else voucher.voucher_date
            lf = ChequeReservationService.reserve_leaf(
                company=company,
                bank_account=ba_obj,
                leaf_id=leaf_id,
                user=user,
                voucher=voucher,
                cheque_date=chq_dt,
                amount=voucher.net_amount or voucher.gross_amount,
                party=voucher.party,
                reason=f"Reserved on voucher draft ({vtype})",
            )
            if not voucher.reference_no:
                voucher.reference_no = lf.cheque_number
                voucher.save(update_fields=["reference_no"])

        from apps.banking.bank_txn_services import BankTransactionService

        BankTransactionService.sync_for_voucher(voucher=voucher)

        VoucherApprovalStep.objects.create(voucher=voucher, actor=user, action="CREATED")
        record_audit_event(
            company=company,
            actor=user,
            device_id=device_id,
            action="VOUCHER_CREATED",
            entity_type="Voucher",
            entity_id=str(voucher.id),
            new_state={"voucher_type": voucher.voucher_type, "status": voucher.status},
        )
        return voucher

    @staticmethod
    @transaction.atomic
    def submit_voucher(*, voucher: Voucher, user, device_id: str = "") -> Voucher:
        voucher = Voucher.objects.select_for_update().get(pk=voucher.pk)
        if voucher.status not in (Voucher.Status.DRAFT, Voucher.Status.REJECTED, Voucher.Status.RETURNED, Voucher.Status.ON_HOLD):
            raise ValidationError(f"Only DRAFT, RETURNED, REJECTED, or ON_HOLD vouchers can be submitted (current: {voucher.status}).")
        resolve_fiscal_context(voucher.company, voucher.voucher_date)
        _validate_voucher_lines(voucher, voucher.lines.select_related("account__parent", "party", "project", "advance_record", "payroll_liability", "staff_loan"))
        plan = PostingRuleEngine.build_voucher_accounting_plan(
            company=voucher.company,
            voucher_type=voucher.voucher_type,
            voucher_date=voucher.voucher_date,
            lines_data=[
                {
                    "account": l.account,
                    "debit": l.debit,
                    "credit": l.credit,
                    "party": l.party,
                    "project": l.project or voucher.project,
                    "advance_record": l.advance_record,
                    "payroll_liability": l.payroll_liability,
                    "staff_loan": l.staff_loan,
                }
                for l in voucher.lines.select_related("account__parent", "party", "project", "advance_record", "payroll_liability", "staff_loan")
            ],
            party=voucher.party,
            supplier_invoice_no=voucher.supplier_invoice_no,
            is_control_override=voucher.is_control_override,
            voucher_id=voucher.id,
        )
        VoucherLogicSnapshot.objects.create(
            company=voucher.company,
            voucher=voucher,
            stage="SUBMITTED",
            is_balanced=plan["is_balanced"],
            is_valid=plan["is_valid"],
            snapshot_payload=plan,
            created_by=user,
        )
        prev = voucher.status
        voucher.status = Voucher.Status.SUBMITTED
        voucher.version += 1
        voucher.save(update_fields=["status", "version", "updated_at"])
        VoucherApprovalStep.objects.create(voucher=voucher, actor=user, action="SUBMITTED")
        record_audit_event(
            company=voucher.company,
            actor=user,
            device_id=device_id,
            action="VOUCHER_SUBMITTED",
            entity_type="Voucher",
            entity_id=str(voucher.id),
            previous_state={"status": prev},
            new_state={"status": voucher.status},
        )
        from apps.accounts_rbac.constants import Permissions
        from apps.notifications.services import DomainEventService

        total_amt = sum((l.debit for l in voucher.lines.all()), Decimal("0.00"))
        DomainEventService.publish(
            event_type="voucher.approval_required",
            title=f"Voucher Approval Required: {voucher.voucher_no or voucher.voucher_type}",
            message=f"{user.full_name or user.username} submitted {voucher.voucher_type} ({voucher.currency} {total_amt:,.2f}) for review.",
            company=voucher.company,
            actor=user,
            category="APPROVAL",
            module="ACCOUNTING",
            priority="HIGH",
            popup_kind="INFO",
            source_object_type="Voucher",
            source_object_id=str(voucher.id),
            source_reference=voucher.voucher_no or str(voucher.id)[:8],
            route_key=f"vouchers:{voucher.voucher_type}",
            required_permission=Permissions.VOUCHER_APPROVE,
            exclude_actor=True,
            project_id=voucher.project_id,
            dedup_key=f"voucher.submit:{voucher.id}:{voucher.version}",
            action_definition={
                "actions": [
                    {"key": "APPROVE_VOUCHER", "label": "Approve", "variant": "primary"},
                    {"key": "REJECT_VOUCHER", "label": "Reject", "variant": "danger"},
                    {"key": "NAVIGATE", "label": "View Voucher", "variant": "secondary"},
                ]
            },
            metadata={"voucher_type": voucher.voucher_type, "amount": str(total_amt), "currency": voucher.currency},
        )
        bump_dashboard_cache(voucher.company_id)
        from apps.accounting.services.concurrency import CacheScopeInvalidator

        transaction.on_commit(lambda cid=str(voucher.company_id): CacheScopeInvalidator.invalidate_company_summaries(cid))
        return voucher

    @staticmethod
    @transaction.atomic
    def convert_provisional_to_regular(
        *,
        voucher: Voucher,
        user,
        target_date: date | None = None,
        effective_date: date | None = None,
        device_id: str = "",
    ) -> Voucher:
        """Converts OPTIONAL / MEMORANDUM / matured POST_DATED voucher into official POSTED book entry."""
        orig = Voucher.objects.select_for_update().prefetch_related("lines__cost_allocations").get(pk=voucher.pk)
        if orig.provisional_kind == Voucher.ProvisionalKind.REGULAR and orig.status == Voucher.Status.POSTED:
            raise ValidationError("Voucher is already a regular posted entry.")
        post_dt = target_date or effective_date or orig.effective_date or orig.voucher_date
        if orig.provisional_kind == Voucher.ProvisionalKind.POST_DATED and post_dt > timezone.localdate():
            raise ValidationError(f"Post-dated voucher cannot mature before effective date {post_dt}.")

        lines_data = [
            {
                "account": l.account,
                "party": l.party,
                "debit": l.debit,
                "credit": l.credit,
                "project": l.project,
                "site": l.site,
                "department": l.department,
                "cost_center": l.cost_center,
                "cost_code": l.cost_code,
                "boq_item": l.boq_item,
                "work_package": l.work_package,
                "description": l.description,
                "cost_allocations": [
                    {
                        "cost_category": ca.cost_category,
                        "cost_center": ca.cost_center,
                        "project": ca.project,
                        "site": ca.site,
                        "allocation_mode": ca.allocation_mode,
                        "percentage": ca.percentage,
                        "amount": ca.amount,
                    }
                    for ca in l.cost_allocations.all()
                ],
            }
            for l in orig.lines.all()
        ]
        target_type = (
            orig.voucher_type_config.parent_type
            if orig.voucher_type_config and orig.voucher_type_config.parent_type not in ("OPTIONAL", "MEMORANDUM", "POST_DATED")
            else (Voucher.VoucherType.JOURNAL if orig.voucher_type in ("OPTIONAL", "MEMORANDUM", "POST_DATED") else orig.voucher_type)
        )
        new_v = VoucherService.create_draft(
            company=orig.company,
            user=user,
            data={
                "voucher_type": target_type,
                "voucher_date": post_dt,
                "due_date": orig.due_date,
                "project": orig.project,
                "site": orig.site,
                "party": orig.party,
                "narration": f"[Converted from {orig.provisional_kind}] {orig.narration}",
                "provisional_kind": Voucher.ProvisionalKind.REGULAR,
                "converted_from": orig,
                "entry_mode": orig.entry_mode,
                "bill_wise_allocations": orig.bill_wise_allocations_payload,
            },
            lines_data=lines_data,
        )
        new_v.status = Voucher.Status.APPROVED
        new_v.approved_by = user
        new_v.save(update_fields=["status", "approved_by"])
        new_v = PostingService.post_voucher(voucher=new_v, user=user)

        VoucherRevision.objects.create(
            company=orig.company,
            voucher=orig,
            version=orig.version,
            changed_by=user,
            change_summary=f"Converted {orig.provisional_kind} to regular posted voucher {new_v.voucher_no}",
            previous_payload={"status": orig.status, "provisional_kind": orig.provisional_kind},
            new_payload={"converted_voucher_no": new_v.voucher_no, "status": "CONVERTED"},
        )
        orig.status = Voucher.Status.CANCELLED
        orig.version += 1
        orig.save(update_fields=["status", "version", "updated_at"])
        return new_v

    @staticmethod
    @transaction.atomic
    def post_reversing_journal_pair(
        *,
        voucher: Voucher,
        user,
        reversal_date: date | None = None,
        device_id: str = "",
    ) -> dict[str, Voucher]:
        """Posts a REVERSING_JOURNAL on voucher_date AND automatically posts its mirrored reversal on reverse_on_date."""
        v = Voucher.objects.select_for_update().prefetch_related("lines").get(pk=voucher.pk)
        rev_dt = reversal_date or v.reverse_on_date
        if not rev_dt:
            raise ValidationError("Reversing Journal requires reverse_on_date.")
        v.provisional_kind = Voucher.ProvisionalKind.REGULAR
        v.status = Voucher.Status.APPROVED
        v.approved_by = user
        v.save(update_fields=["provisional_kind", "status", "approved_by"])
        posted = PostingService.post_voucher(voucher=v, user=user, device_id=device_id)
        rev = PostingService.reverse_voucher(
            voucher=posted,
            user=user,
            reversal_date=rev_dt,
            reason=f"Auto-Reversal of Reversing Journal {posted.voucher_no}",
            device_id=device_id,
        )
        return {"primary": posted, "reversal": rev}


class ApprovalService:
    @staticmethod
    @transaction.atomic
    def transition_status(*, voucher: Voucher, user, target_status: str, comment: str = "", device_id: str = "") -> Voucher:
        voucher = Voucher.objects.select_for_update().get(pk=voucher.pk)
        allowed = {
            Voucher.Status.UNDER_REVIEW: (Voucher.Status.SUBMITTED,),
            Voucher.Status.RETURNED: (Voucher.Status.SUBMITTED, Voucher.Status.UNDER_REVIEW, Voucher.Status.ON_HOLD),
            Voucher.Status.ON_HOLD: (Voucher.Status.SUBMITTED, Voucher.Status.UNDER_REVIEW, Voucher.Status.APPROVED),
            Voucher.Status.CANCELLED: (Voucher.Status.DRAFT, Voucher.Status.RETURNED, Voucher.Status.REJECTED, Voucher.Status.ON_HOLD),
        }
        if target_status not in allowed or voucher.status not in allowed[target_status]:
            raise ValidationError(f"Cannot transition voucher from {voucher.status} to {target_status}.")
        prev = voucher.status
        voucher.status = target_status
        voucher.version += 1
        voucher.save(update_fields=["status", "version", "updated_at"])
        if target_status == Voucher.Status.CANCELLED:
            from apps.banking.bank_txn_services import ChequeReservationService

            ChequeReservationService.handle_voucher_cancel_or_reverse(
                voucher=voucher, user=user, reason=comment
            )
        VoucherApprovalStep.objects.create(voucher=voucher, actor=user, action=target_status, comment=comment)
        record_audit_event(
            company=voucher.company,
            actor=user,
            device_id=device_id,
            action=f"VOUCHER_{target_status}",
            entity_type="Voucher",
            entity_id=str(voucher.id),
            previous_state={"status": prev},
            new_state={"status": voucher.status, "comment": comment},
        )
        bump_dashboard_cache(voucher.company_id)
        from apps.accounting.services.concurrency import CacheScopeInvalidator

        transaction.on_commit(lambda cid=str(voucher.company_id): CacheScopeInvalidator.invalidate_company_summaries(cid))
        return voucher

    @staticmethod
    @transaction.atomic
    def approve_voucher(*, voucher: Voucher, user, comment: str = "", device_id: str = "") -> Voucher:
        voucher = Voucher.objects.select_for_update().get(pk=voucher.pk)
        if voucher.status not in (Voucher.Status.SUBMITTED, Voucher.Status.UNDER_REVIEW):
            raise ValidationError(f"Only SUBMITTED or UNDER_REVIEW vouchers can be approved (current: {voucher.status}).")
        if voucher.created_by_id == user.id and not user.is_superuser:
            raise ValidationError("Maker-checker control: creator cannot approve their own voucher.")
        total_amt = sum((l.debit for l in voucher.lines.all()), Decimal("0.00"))
        membership = (
            CompanyMembership.objects.select_related("role")
            .prefetch_related("roles")
            .filter(user=user, company=voucher.company, is_active=True)
            .first()
        )
        check_approval_authority(
            company=voucher.company,
            membership=membership,
            user=user,
            voucher_type=voucher.voucher_type,
            amount=total_amt,
            currency=voucher.currency,
        )
        prev = voucher.status
        voucher.status = Voucher.Status.APPROVED
        voucher.approved_by = user
        voucher.version += 1
        voucher.save(update_fields=["status", "approved_by", "version", "updated_at"])
        VoucherApprovalStep.objects.create(voucher=voucher, actor=user, action="APPROVED", comment=comment)
        record_audit_event(
            company=voucher.company,
            actor=user,
            device_id=device_id,
            action="VOUCHER_APPROVED",
            entity_type="Voucher",
            entity_id=str(voucher.id),
            previous_state={"status": prev},
            new_state={"status": voucher.status, "comment": comment},
        )
        from apps.accounts_rbac.constants import Permissions
        from apps.notifications.services import DomainEventService

        if voucher.created_by_id:
            DomainEventService.publish(
                event_type="voucher.approved",
                title=f"Voucher Approved: {voucher.voucher_no or voucher.voucher_type}",
                message=f"Approved by {user.full_name or user.username}. Ready for ledger posting.",
                company=voucher.company,
                actor=user,
                category="ACCOUNTING",
                module="ACCOUNTING",
                priority="NORMAL",
                popup_kind="SUCCESS",
                source_object_type="Voucher",
                source_object_id=str(voucher.id),
                source_reference=voucher.voucher_no or str(voucher.id)[:8],
                route_key=f"vouchers:{voucher.voucher_type}",
                recipient_ids=[voucher.created_by_id],
                dedup_key=f"voucher.approved:{voucher.id}:{voucher.version}",
                action_definition={
                    "actions": [
                        {"key": "POST_VOUCHER", "label": "Post Now", "variant": "primary"},
                        {"key": "NAVIGATE", "label": "View Voucher", "variant": "secondary"},
                    ]
                },
            )
        bump_dashboard_cache(voucher.company_id)
        from apps.accounting.services.concurrency import CacheScopeInvalidator

        transaction.on_commit(lambda cid=str(voucher.company_id): CacheScopeInvalidator.invalidate_company_summaries(cid))
        return voucher

    @staticmethod
    @transaction.atomic
    def reject_voucher(*, voucher: Voucher, user, reason: str = "", device_id: str = "") -> Voucher:
        voucher = Voucher.objects.select_for_update().get(pk=voucher.pk)
        if voucher.status not in (Voucher.Status.SUBMITTED, Voucher.Status.UNDER_REVIEW, Voucher.Status.APPROVED):
            raise ValidationError(f"Cannot reject voucher in status {voucher.status}.")
        prev = voucher.status
        voucher.status = Voucher.Status.REJECTED
        voucher.version += 1
        voucher.save(update_fields=["status", "version", "updated_at"])
        VoucherApprovalStep.objects.create(voucher=voucher, actor=user, action="REJECTED", comment=reason)
        record_audit_event(
            company=voucher.company,
            actor=user,
            device_id=device_id,
            action="VOUCHER_REJECTED",
            entity_type="Voucher",
            entity_id=str(voucher.id),
            previous_state={"status": prev},
            new_state={"status": voucher.status, "reason": reason},
        )
        from apps.accounts_rbac.constants import Permissions
        from apps.notifications.services import DomainEventService

        if voucher.created_by_id:
            DomainEventService.publish(
                event_type="voucher.rejected",
                title=f"Voucher Rejected: {voucher.voucher_no or voucher.voucher_type}",
                message=reason or "Returned by reviewer for correction.",
                company=voucher.company,
                actor=user,
                category="ACCOUNTING",
                module="ACCOUNTING",
                priority="HIGH",
                popup_kind="WARNING",
                source_object_type="Voucher",
                source_object_id=str(voucher.id),
                source_reference=voucher.voucher_no or str(voucher.id)[:8],
                route_key=f"vouchers:{voucher.voucher_type}",
                recipient_ids=[voucher.created_by_id],
                dedup_key=f"voucher.rejected:{voucher.id}:{voucher.version}",
            )
        bump_dashboard_cache(voucher.company_id)
        from apps.accounting.services.concurrency import CacheScopeInvalidator

        transaction.on_commit(lambda cid=str(voucher.company_id): CacheScopeInvalidator.invalidate_company_summaries(cid))
        return voucher


class PostingService:
    @staticmethod
    def _next_voucher_no(voucher: Voucher) -> str:
        cfg = voucher.voucher_type_config
        if cfg and cfg.numbering_method == "MANUAL":
            if not voucher.voucher_no:
                raise ValidationError(f"Manual voucher number is required for '{cfg.name}'.")
            return voucher.voucher_no

        fy_tag = voucher.fiscal_year.name.replace("/", "")
        series = (cfg.series_code if cfg else "DEFAULT") or "DEFAULT"
        reset_freq = cfg.reset_frequency if cfg else "YEARLY"
        bs_month_tag = (voucher.bs_date or ad_to_bs(voucher.voucher_date).isoformat())[:7].replace("-", "")
        period_tag = (
            "ALL"
            if reset_freq == "NEVER"
            else (bs_month_tag if reset_freq == "MONTHLY" else fy_tag)
        )
        vkey = cfg.code if cfg else voucher.voucher_type
        start_base = max((cfg.starting_number if cfg else 1) - 1, 0)

        seq, _ = VoucherSequence.objects.select_for_update().get_or_create(
            company=voucher.company,
            fiscal_year=voucher.fiscal_year,
            voucher_type=vkey,
            series_code=series,
            period_tag=period_tag,
            defaults={"last_number": start_base},
        )
        seq.last_number += 1
        seq.save(update_fields=["last_number"])

        prefix = ((cfg.prefix if cfg and cfg.prefix else None) or VOUCHER_PREFIX.get(voucher.voucher_type, voucher.voucher_type[:3])).rstrip("-")
        suffix = cfg.suffix if cfg else ""
        pad = cfg.zero_pad_width if cfg else 5
        num_str = f"{seq.last_number:0{pad}d}"
        core_no = f"{prefix}-{period_tag}-{num_str}"
        return f"{core_no}-{suffix}" if suffix else core_no

    @staticmethod
    @transaction.atomic
    def post_voucher(*, voucher: Voucher, user, device_id: str = "") -> Voucher:
        voucher = Voucher.objects.select_for_update().get(pk=voucher.pk)
        if voucher.status == Voucher.Status.POSTED:
            return voucher
        if voucher.status != Voucher.Status.APPROVED:
            raise ValidationError(
                f"Voucher must be APPROVED before posting (current: {voucher.status})."
            )
        if voucher.provisional_kind in (Voucher.ProvisionalKind.OPTIONAL, Voucher.ProvisionalKind.MEMORANDUM):
            raise ValidationError(
                f"{voucher.provisional_kind} provisional vouchers cannot post directly to the General Ledger. Convert to regular voucher first."
            )
        if voucher.provisional_kind == Voucher.ProvisionalKind.POST_DATED and (voucher.effective_date or voucher.voucher_date) > timezone.localdate():
            raise ValidationError(
                f"Post-dated voucher is effective on {voucher.effective_date or voucher.voucher_date} and cannot enter official books earlier."
            )

        fy, period = resolve_fiscal_context(voucher.company, voucher.voucher_date)
        lines = list(voucher.lines.select_related("account__parent", "party", "project", "site", "department", "cost_center", "cost_code", "boq_item", "work_package", "contractor", "equipment", "advance_record", "payroll_liability", "staff_loan", "against_voucher").prefetch_related("cost_allocations"))
        plan = PostingRuleEngine.build_voucher_accounting_plan(
            company=voucher.company,
            voucher_type=voucher.voucher_type,
            voucher_date=voucher.voucher_date,
            lines_data=[
                {
                    "account": l.account,
                    "debit": l.debit,
                    "credit": l.credit,
                    "party": l.party,
                    "project": l.project or voucher.project,
                    "cost_center": l.cost_center or voucher.cost_center,
                    "advance_record": l.advance_record,
                    "payroll_liability": l.payroll_liability,
                    "staff_loan": l.staff_loan,
                    "cost_allocations": [
                        {
                            "allocation_mode": ca.allocation_mode,
                            "percentage": ca.percentage,
                            "amount": ca.amount,
                        }
                        for ca in l.cost_allocations.all()
                    ],
                }
                for l in lines
            ],
            party=voucher.party,
            supplier_invoice_no=voucher.supplier_invoice_no,
            is_control_override=voucher.is_control_override,
            voucher_id=voucher.id,
            voucher_type_config=voucher.voucher_type_config,
        )
        if not plan["is_valid"]:
            raise ValidationError(plan["validation_errors"])

        from apps.banking.bank_txn_services import BankTransactionService, ChequeReservationService

        ChequeReservationService.validate_and_issue_on_post(voucher=voucher, user=user)

        total_debit = Decimal(plan["total_debit"])
        if not voucher.voucher_no:
            voucher.voucher_no = PostingService._next_voucher_no(voucher)

        now = timezone.now()
        q = Decimal("0.01")
        rate = voucher.exchange_rate or Decimal("1.000000")
        bs_str = voucher.bs_date or ad_to_bs(voucher.voucher_date).isoformat()

        for line in lines:
            base_debit = (line.debit * rate).quantize(q, rounding=ROUND_HALF_UP)
            base_credit = (line.credit * rate).quantize(q, rounding=ROUND_HALF_UP)
            line_party = line.party or voucher.party
            LedgerEntry.objects.create(
                company=voucher.company,
                branch=voucher.branch,
                fiscal_year=fy,
                fiscal_period=period,
                voucher=voucher,
                voucher_line=line,
                account=line.account,
                party=line_party,
                posting_date=voucher.voucher_date,
                bs_date=bs_str,
                transaction_currency=voucher.currency,
                exchange_rate=rate,
                debit=line.debit,
                credit=line.credit,
                base_debit=base_debit,
                base_credit=base_credit,
                project=line.project or voucher.project,
                site=line.site or voucher.site,
                department=line.department or voucher.department,
                cost_center=line.cost_center or voucher.cost_center,
                cost_code=line.cost_code,
                boq_item=line.boq_item,
                work_package=line.work_package,
                work_activity=line.work_activity,
                contractor=line.contractor,
                equipment=line.equipment,
                employee_ref=line.employee_ref,
                narration=line.description or voucher.narration,
                posted_at=now,
            )

            # Write append-only PartyLedgerEntry when touching debtor/creditor/subcontractor/employee/advance control accounts
            if line_party and line.account.control_role in (
                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,
                Account.ControlRole.EMPLOYEE_PAYABLE,
                Account.ControlRole.WAGES_PAYABLE,
                Account.ControlRole.EMPLOYEE_REIMBURSEMENT,
                Account.ControlRole.EMPLOYEE_ADVANCE,
                Account.ControlRole.STAFF_LOAN_RECEIVABLE,
            ):
                entry_kind = PartyLedgerEntry.EntryKind.INVOICE
                if voucher.voucher_type in ("PAYMENT", "LABOR_PAYMENT", "SUBCONTRACTOR_PAYMENT"):
                    entry_kind = PartyLedgerEntry.EntryKind.PAYMENT
                elif voucher.voucher_type == "RECEIPT":
                    entry_kind = PartyLedgerEntry.EntryKind.RECEIPT
                elif voucher.voucher_type in ("JOURNAL", "ADVANCE_SETTLEMENT", "STAFF_SETTLEMENT"):
                    entry_kind = PartyLedgerEntry.EntryKind.ADJUSTMENT
                elif line.account.control_role in (Account.ControlRole.RETENTION_PAYABLE, Account.ControlRole.RETENTION_RECEIVABLE):
                    entry_kind = PartyLedgerEntry.EntryKind.RETENTION
                elif line.account.control_role in (Account.ControlRole.CUSTOMER_ADVANCE, Account.ControlRole.SUPPLIER_ADVANCE, Account.ControlRole.EMPLOYEE_ADVANCE):
                    entry_kind = PartyLedgerEntry.EntryKind.ADVANCE

                PartyLedgerEntry.objects.create(
                    company=voucher.company,
                    party=line_party,
                    control_account=line.account,
                    voucher=voucher,
                    project=line.project or voucher.project,
                    entry_date=voucher.voucher_date,
                    bs_date=bs_str,
                    due_date=line.due_date or voucher.due_date,
                    entry_kind=entry_kind,
                    reference_no=line.bill_ref or voucher.supplier_invoice_no or voucher.reference_no or voucher.voucher_no,
                    debit=base_debit,
                    credit=base_credit,
                    retention_amount=(base_debit or base_credit) if entry_kind == PartyLedgerEntry.EntryKind.RETENTION else Decimal("0.00"),
                    advance_adjusted=(base_debit or base_credit) if line.advance_record_id else Decimal("0.00"),
                    narration=line.description or voucher.narration[:255],
                )

        AdvanceAdjustmentService.apply_voucher_references_on_post(voucher=voucher, user=user)
        VoucherLogicSnapshot.objects.create(
            company=voucher.company,
            voucher=voucher,
            stage="POSTED",
            is_balanced=plan["is_balanced"],
            is_valid=plan["is_valid"],
            snapshot_payload=plan,
            created_by=user,
        )

        voucher.status = Voucher.Status.POSTED
        voucher.posted_by = user
        voucher.posted_at = now
        voucher.logic_snapshot = plan
        voucher.version += 1
        voucher.save(
            update_fields=["voucher_no", "status", "posted_by", "posted_at", "logic_snapshot", "version", "updated_at"]
        )

        from apps.party_hub.services.sync import OpenItemSyncService
        OpenItemSyncService.sync_voucher_open_items(voucher=voucher)
        if voucher.bill_wise_allocations_payload and voucher.party:
            from apps.party_hub.models import OpenItem
            from apps.party_hub.services.allocation import InvoiceAllocationService
            against_rows = [
                {
                    "open_item_id": r["open_item_id"],
                    "allocated_amount": r.get("allocated_amount") or r.get("amount"),
                    "amount": r.get("amount") or r.get("allocated_amount"),
                    "tds_adjusted": r.get("tds_adjusted", "0.00"),
                    "discount_adjusted": r.get("discount_adjusted", "0.00"),
                    "writeoff_amount": r.get("writeoff_amount", "0.00"),
                }
                for r in voucher.bill_wise_allocations_payload
                if r.get("ref_type") == "AGAINST_REF" and r.get("open_item_id")
            ]
            if against_rows:
                side = (
                    OpenItem.HubSide.RECEIVABLE
                    if voucher.party.party_type == Party.PartyType.CUSTOMER
                    else OpenItem.HubSide.PAYABLE
                )
                InvoiceAllocationService.allocate_batch(
                    company=voucher.company,
                    user=user,
                    party=voucher.party,
                    settlement_voucher=voucher,
                    allocations=against_rows,
                    hub_side=side,
                )

        # Exact-once inventory movement hook for stock & material vouchers
        stock_vtypes = (
            "RECEIPT_NOTE", "DELIVERY_NOTE", "REJECTIONS_IN", "REJECTIONS_OUT",
            "STOCK_JOURNAL", "PHYSICAL_STOCK", "MATERIAL_IN", "MATERIAL_OUT",
            "MANUFACTURING_JOURNAL", "MATERIAL_ISSUE", "MATERIAL_RETURN",
        )
        inv_rows = list(voucher.inventory_items.select_related("item", "warehouse", "target_warehouse").all())
        if voucher.voucher_type in stock_vtypes and inv_rows:
            from apps.inventory.models import StockMovement
            if not StockMovement.objects.filter(voucher=voucher).exists():
                outward_types = ("DELIVERY_NOTE", "REJECTIONS_OUT", "MATERIAL_ISSUE", "MATERIAL_OUT", "STOCK_JOURNAL")
                mtype_map = {
                    "RECEIPT_NOTE": StockMovement.MovementType.GRN_RECEIPT,
                    "MATERIAL_RETURN": StockMovement.MovementType.RETURN,
                    "REJECTIONS_IN": StockMovement.MovementType.RETURN,
                    "MATERIAL_ISSUE": StockMovement.MovementType.ISSUE,
                    "DELIVERY_NOTE": StockMovement.MovementType.ISSUE,
                    "REJECTIONS_OUT": StockMovement.MovementType.ADJUSTMENT,
                    "STOCK_JOURNAL": StockMovement.MovementType.TRANSFER_OUT,
                    "PHYSICAL_STOCK": StockMovement.MovementType.COUNT_VARIANCE,
                    "MATERIAL_IN": StockMovement.MovementType.RETURN,
                    "MATERIAL_OUT": StockMovement.MovementType.ISSUE,
                    "MANUFACTURING_JOURNAL": StockMovement.MovementType.ADJUSTMENT,
                }
                for irow in inv_rows:
                    if not irow.warehouse:
                        continue
                    prev_agg = StockMovement.objects.filter(
                        company=voucher.company, warehouse=irow.warehouse, item=irow.item
                    ).aggregate(q=Sum("quantity_delta"), v=Sum("value_delta"))
                    prev_q = prev_agg["q"] or Decimal("0.000")
                    prev_v = prev_agg["v"] or Decimal("0.00")
                    is_out = voucher.voucher_type in outward_types
                    q_delta = -abs(irow.quantity) if is_out else abs(irow.quantity)
                    if is_out and (prev_q + q_delta) < Decimal("0.000"):
                        raise ValidationError(
                            f"Insufficient stock for {irow.item.item_code} in {irow.warehouse.code} (available {prev_q}, requested {abs(q_delta)})."
                        )
                    v_delta = -abs(irow.amount) if is_out else abs(irow.amount)
                    StockMovement.objects.create(
                        company=voucher.company,
                        warehouse=irow.warehouse,
                        item=irow.item,
                        movement_type=mtype_map.get(voucher.voucher_type, StockMovement.MovementType.ADJUSTMENT),
                        movement_date=voucher.voucher_date,
                        reference_no=voucher.voucher_no,
                        quantity_delta=q_delta,
                        unit_cost=irow.rate,
                        value_delta=v_delta,
                        balance_qty_after=prev_q + q_delta,
                        balance_value_after=prev_v + v_delta,
                        project=voucher.project,
                        site=voucher.site,
                        voucher=voucher,
                        created_by=user,
                    )
                    if voucher.voucher_type == "STOCK_JOURNAL" and irow.target_warehouse:
                        dst_agg = StockMovement.objects.filter(
                            company=voucher.company, warehouse=irow.target_warehouse, item=irow.item
                        ).aggregate(q=Sum("quantity_delta"), v=Sum("value_delta"))
                        dq = dst_agg["q"] or Decimal("0.000")
                        dv = dst_agg["v"] or Decimal("0.00")
                        StockMovement.objects.create(
                            company=voucher.company,
                            warehouse=irow.target_warehouse,
                            item=irow.item,
                            movement_type=StockMovement.MovementType.TRANSFER_IN,
                            movement_date=voucher.voucher_date,
                            reference_no=voucher.voucher_no,
                            quantity_delta=abs(irow.quantity),
                            unit_cost=irow.rate,
                            value_delta=abs(irow.amount),
                            balance_qty_after=dq + abs(irow.quantity),
                            balance_value_after=dv + abs(irow.amount),
                            project=voucher.project,
                            site=voucher.site,
                            voucher=voucher,
                            created_by=user,
                        )

        VoucherApprovalStep.objects.create(voucher=voucher, actor=user, action="POSTED")
        BankTransactionService.sync_for_voucher(voucher=voucher)
        record_audit_event(
            company=voucher.company,
            actor=user,
            device_id=device_id,
            action="VOUCHER_POSTED",
            entity_type="Voucher",
            entity_id=str(voucher.id),
            new_state={"voucher_no": voucher.voucher_no, "total": str(total_debit)},
        )
        from apps.accounts_rbac.constants import Permissions
        from apps.notifications.services import DomainEventService

        notify_ids = list({x for x in (getattr(user, "id", None), voucher.created_by_id) if x})
        DomainEventService.publish(
            event_type="voucher.posted",
            title=f"Voucher Posted: {voucher.voucher_no}",
            message=f"{voucher.voucher_type} ({voucher.currency} {total_debit:,.2f}) posted to General Ledger.",
            company=voucher.company,
            actor=user,
            category="ACCOUNTING",
            module="ACCOUNTING",
            priority="NORMAL",
            popup_kind="SUCCESS",
            source_object_type="Voucher",
            source_object_id=str(voucher.id),
            source_reference=voucher.voucher_no,
            route_key=f"vouchers:{voucher.voucher_type}",
            recipient_ids=notify_ids,
            dedup_key=f"voucher.posted:{voucher.id}:{voucher.version}",
            metadata={"voucher_no": voucher.voucher_no, "total": str(total_debit)},
        )
        bump_dashboard_cache(voucher.company_id)
        from apps.accounting.services.concurrency import CacheScopeInvalidator

        transaction.on_commit(lambda cid=str(voucher.company_id): CacheScopeInvalidator.invalidate_company_summaries(cid))
        return voucher

    @staticmethod
    @transaction.atomic
    def reverse_voucher(*, voucher: Voucher, user, reversal_date: date, reason: str = "", device_id: str = "") -> Voucher:
        original = Voucher.objects.select_for_update().get(pk=voucher.pk)
        if original.status != Voucher.Status.POSTED:
            raise ValidationError("Only POSTED vouchers can be reversed.")

        fy, period = resolve_fiscal_context(original.company, reversal_date)
        rev_voucher = Voucher.objects.create(
            company=original.company,
            branch=original.branch,
            fiscal_year=fy,
            fiscal_period=period,
            voucher_type=Voucher.VoucherType.REVERSAL,
            voucher_date=reversal_date,
            bs_date=ad_to_bs(reversal_date).isoformat(),
            currency=original.currency,
            exchange_rate=original.exchange_rate,
            project=original.project,
            site=original.site,
            party=original.party,
            is_control_override=original.is_control_override,
            override_reason=f"Reversal of {original.voucher_no}",
            narration=f"Reversal of {original.voucher_no}: {reason}".strip(),
            status=Voucher.Status.APPROVED,
            reversed_from=original,
            created_by=user,
            approved_by=user,
        )

        for idx, line in enumerate(original.lines.all(), start=1):
            VoucherLine.objects.create(
                voucher=rev_voucher,
                line_no=idx,
                account=line.account,
                party=line.party,
                debit=line.credit,
                credit=line.debit,
                project=line.project,
                site=line.site,
                department=line.department,
                cost_center=line.cost_center,
                cost_code=line.cost_code,
                boq_item=line.boq_item,
                work_package=line.work_package,
                equipment=line.equipment,
                bill_ref=line.bill_ref,
                due_date=line.due_date,
                description=f"Reversal: {line.description or original.voucher_no}",
            )

        rev_voucher = PostingService.post_voucher(
            voucher=rev_voucher, user=user, device_id=device_id
        )
        from apps.party_hub.services.sync import OpenItemSyncService
        OpenItemSyncService.handle_voucher_reversal(original=original, reversal=rev_voucher)

        from apps.banking.bank_txn_services import ChequeReservationService
        ChequeReservationService.handle_voucher_cancel_or_reverse(
            voucher=original, user=user, reversal_voucher=rev_voucher, reason=reason
        )

        original.status = Voucher.Status.REVERSED
        original.version += 1
        original.save(update_fields=["status", "version", "updated_at"])

        record_audit_event(
            company=original.company,
            actor=user,
            device_id=device_id,
            action="VOUCHER_REVERSED",
            entity_type="Voucher",
            entity_id=str(original.id),
            previous_state={"status": Voucher.Status.POSTED},
            new_state={"status": Voucher.Status.REVERSED, "reversal_voucher_no": rev_voucher.voucher_no},
        )
        bump_dashboard_cache(original.company_id)
        return rev_voucher


class LedgerService:
    @staticmethod
    def get_account_ledger(*, company, account: Account, date_from: date | None = None, date_to: date | None = None, project_id: str | None = None):
        qs = LedgerEntry.objects.select_related("voucher", "project", "cost_code", "party").filter(
            company=company, account=account
        )
        if project_id:
            qs = qs.filter(project_id=project_id)

        opening_net = account.opening_debit - account.opening_credit
        if date_from:
            prior = qs.filter(posting_date__lt=date_from).aggregate(
                d=Sum("base_debit"), c=Sum("base_credit")
            )
            opening_net += (prior["d"] or Decimal("0.00")) - (prior["c"] or Decimal("0.00"))
            qs = qs.filter(posting_date__gte=date_from)
        if date_to:
            qs = qs.filter(posting_date__lte=date_to)

        running = opening_net
        rows = []
        total_debit = Decimal("0.00")
        total_credit = Decimal("0.00")
        for entry in qs:
            running += entry.base_debit - entry.base_credit
            total_debit += entry.base_debit
            total_credit += entry.base_credit
            rows.append(
                {
                    "id": str(entry.id),
                    "posting_date": entry.posting_date.isoformat(),
                    "bs_date": entry.bs_date,
                    "voucher_id": str(entry.voucher_id),
                    "voucher_no": entry.voucher.voucher_no,
                    "voucher_type": entry.voucher.voucher_type,
                    "party_name": entry.party.name if entry.party else "",
                    "project_code": entry.project.code if entry.project else None,
                    "cost_code": entry.cost_code.code if entry.cost_code else None,
                    "narration": entry.narration,
                    "debit": str(entry.base_debit),
                    "credit": str(entry.base_credit),
                    "running_balance": str(abs(running)),
                    "running_side": "Dr" if running >= 0 else "Cr",
                }
            )

        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,
            },
            "opening_balance": str(abs(opening_net)),
            "opening_side": "Dr" if opening_net >= 0 else "Cr",
            "total_debit": str(total_debit),
            "total_credit": str(total_credit),
            "closing_balance": str(abs(running)),
            "closing_side": "Dr" if running >= 0 else "Cr",
            "entries": rows,
        }


class ReportingService:
    @staticmethod
    def get_trial_balance(*, company, date_to: date | None = None, project_id: str | None = None):
        accounts = Account.objects.filter(company=company, is_group=False, is_active=True).order_by("code")
        entry_qs = LedgerEntry.objects.filter(company=company)
        if date_to:
            entry_qs = entry_qs.filter(posting_date__lte=date_to)
        if project_id:
            entry_qs = entry_qs.filter(project_id=project_id)

        sums = {
            row["account_id"]: row
            for row in entry_qs.values("account_id").annotate(
                ob_debit=Sum("base_debit", filter=Q(voucher__voucher_type=Voucher.VoucherType.OPENING_BALANCE)),
                ob_credit=Sum("base_credit", filter=Q(voucher__voucher_type=Voucher.VoucherType.OPENING_BALANCE)),
                period_debit=Sum("base_debit", filter=~Q(voucher__voucher_type=Voucher.VoucherType.OPENING_BALANCE)),
                period_credit=Sum("base_credit", filter=~Q(voucher__voucher_type=Voucher.VoucherType.OPENING_BALANCE)),
            )
        }

        rows = []
        grand_debit = Decimal("0.00")
        grand_credit = Decimal("0.00")
        for acc in accounts:
            agg = sums.get(acc.id, {})
            open_d = acc.opening_debit + (agg.get("ob_debit") or Decimal("0.00"))
            open_c = acc.opening_credit + (agg.get("ob_credit") or Decimal("0.00"))
            period_d = agg.get("period_debit") or Decimal("0.00")
            period_c = agg.get("period_credit") or Decimal("0.00")
            net = (open_d - open_c) + (period_d - period_c)
            closing_d = net if net > 0 else Decimal("0.00")
            closing_c = -net if net < 0 else Decimal("0.00")
            if open_d == 0 and open_c == 0 and period_d == 0 and period_c == 0:
                continue
            grand_debit += closing_d
            grand_credit += closing_c
            rows.append(
                {
                    "account_id": str(acc.id),
                    "code": acc.code,
                    "name": acc.name,
                    "account_type": acc.account_type,
                    "account_class": acc.effective_class,
                    "opening_debit": str(open_d),
                    "opening_credit": str(open_c),
                    "period_debit": str(period_d),
                    "period_credit": str(period_c),
                    "closing_debit": str(closing_d),
                    "closing_credit": str(closing_c),
                }
            )

        return {
            "rows": rows,
            "total_debit": str(grand_debit),
            "total_credit": str(grand_credit),
            "is_balanced": grand_debit == grand_credit,
        }

    @staticmethod
    def get_profit_and_loss(*, company, date_from: date | None = None, date_to: date | None = None, project_id: str | None = None):
        qs = LedgerEntry.objects.select_related("account").filter(
            company=company,
            account__account_type__in=[Account.AccountType.INCOME, Account.AccountType.EXPENSE],
        )
        if date_from:
            qs = qs.filter(posting_date__gte=date_from)
        if date_to:
            qs = qs.filter(posting_date__lte=date_to)
        if project_id:
            qs = qs.filter(project_id=project_id)

        rows = qs.values(
            "account_id", "account__code", "account__name", "account__account_type"
        ).annotate(d=Sum("base_debit"), c=Sum("base_credit"))

        income_items = []
        expense_items = []
        total_income = Decimal("0.00")
        total_expense = Decimal("0.00")

        for r in rows:
            d = r["d"] or Decimal("0.00")
            c = r["c"] or Decimal("0.00")
            if r["account__account_type"] == Account.AccountType.INCOME:
                amt = c - d
                total_income += amt
                income_items.append({"account_id": str(r["account_id"]), "code": r["account__code"], "name": r["account__name"], "amount": str(amt)})
            else:
                amt = d - c
                total_expense += amt
                expense_items.append({"account_id": str(r["account_id"]), "code": r["account__code"], "name": r["account__name"], "amount": str(amt)})

        net_profit = total_income - total_expense
        return {
            "income": income_items,
            "expenses": expense_items,
            "total_income": str(total_income),
            "total_expense": str(total_expense),
            "net_profit": str(net_profit),
        }

    @staticmethod
    def get_balance_sheet(*, company, date_to: date | None = None):
        tb = ReportingService.get_trial_balance(company=company, date_to=date_to)
        assets, liabilities, equity = [], [], []
        total_assets = Decimal("0.00")
        total_liabilities = Decimal("0.00")
        total_equity = Decimal("0.00")
        net_income = Decimal("0.00")

        for row in tb["rows"]:
            d = Decimal(row["closing_debit"])
            c = Decimal(row["closing_credit"])
            atype = row["account_type"]
            if atype == Account.AccountType.ASSET:
                bal = d - c
                total_assets += bal
                assets.append({**row, "balance": str(bal)})
            elif atype == Account.AccountType.LIABILITY:
                bal = c - d
                total_liabilities += bal
                liabilities.append({**row, "balance": str(bal)})
            elif atype == Account.AccountType.EQUITY:
                bal = c - d
                total_equity += bal
                equity.append({**row, "balance": str(bal)})
            elif atype == Account.AccountType.INCOME:
                net_income += c - d
            elif atype == Account.AccountType.EXPENSE:
                net_income -= d - c

        total_liab_equity = total_liabilities + total_equity + net_income
        return {
            "assets": assets,
            "liabilities": liabilities,
            "equity": equity,
            "current_period_profit": str(net_income),
            "total_assets": str(total_assets),
            "total_liabilities_and_equity": str(total_liab_equity),
            "is_balanced": total_assets == total_liab_equity,
        }

