from datetime import date
from decimal import Decimal
from django.db import transaction

from apps.accounting.models import Account, CostCenter, Party, Voucher
from apps.accounting.services import PostingRuleEngine, PostingService, VoucherService
from apps.accounts_rbac.constants import Permissions
from apps.accounts_rbac.models import CompanyMembership
from apps.fleet.models import (
    Vehicle,
    VehicleAdvance,
    VehicleCustomerBilling,
    VehicleExpense,
    VehicleIncome,
    VehicleRentalAgreement,
    VehicleSecurityDeposit,
    VehicleSupplierBilling,
    VehicleTrip,
)
from apps.notifications.services import DomainEventService
from apps.party_hub.models import OpenItem
from apps.party_hub.services.allocation import InvoiceAllocationService
from apps.projects.models import CostCode, Project, Site
from apps.tenancy.models import Branch, Company
from .coa_defaults import FleetAccountResolver, record_fleet_audit


def _user_can_post_immediately(company: Company, user) -> bool:
    if user.is_superuser:
        return True
    mem = CompanyMembership.objects.select_related("role").prefetch_related("roles").filter(
        user=user, company=company, is_active=True
    ).first()
    if not mem:
        return False
    return bool({Permissions.VOUCHER_POST, Permissions.VEHICLE_VOUCHER_POST} & set(mem.effective_permissions()))


def _finalize_voucher(company: Company, voucher: Voucher, actor, post_now: bool = True) -> Voucher:
    if post_now and _user_can_post_immediately(company, actor):
        voucher.status = Voucher.Status.APPROVED
        voucher.approved_by = actor
        voucher.save(update_fields=["status", "approved_by"])
        return PostingService.post_voucher(voucher=voucher, user=actor)
    return VoucherService.submit_voucher(voucher=voucher, user=actor)


class VehicleAccountingPostingService:
    """
    Single server-side transaction & preview builder for ALL Vehicle financial entries
    (Single Entry Cash/Bank Income & Expense, Double Entry Customer/Supplier Credit, Deposits).
    """

    @staticmethod
    def build_preview(*, company: Company, payload: dict) -> dict:
        kind = (payload.get("transaction_kind") or "INCOME").upper()  # INCOME|EXPENSE
        entry_mode = (payload.get("entry_mode") or "SINGLE_ENTRY").upper()  # SINGLE_ENTRY|DOUBLE_ENTRY
        payment_method = (payload.get("payment_method") or "CASH").upper()  # CASH|BANK|CREDIT
        amount = Decimal(str(payload.get("amount") or payload.get("gross_amount") or "0.00")).quantize(Decimal("0.01"))
        if amount <= 0:
            raise ValueError("Transaction amount must exceed zero.")

        vehicle = Vehicle.objects.get(company=company, id=payload["vehicle_id"])
        accounts = FleetAccountResolver.ensure_fleet_accounts(company)

        if entry_mode == "SINGLE_ENTRY":
            if payment_method == "CREDIT":
                raise ValueError("Credit / Outstanding is NOT allowed in Single Entry mode. Select Cash or Bank, or switch to Double Entry.")
            if payload.get("party_id"):
                raise ValueError("Single Entry mode does not use Customer or Supplier Party accounts.")
            party = None
        else:
            if not payload.get("party_id"):
                raise ValueError("Double Entry mode strictly requires selecting a Customer or Supplier Party.")
            party = Party.objects.get(company=company, id=payload["party_id"])

        if kind == "INCOME":
            if vehicle.ownership_type == Vehicle.OwnershipType.RENTED_IN:
                raise ValueError("Externally RENTED-IN vehicles cannot post Owned Vehicle Hire Income.")
            if party and party.party_type != "CUSTOMER":
                raise ValueError("Vehicle Income requires a CUSTOMER party.")
            inc_acc = (
                Account.objects.filter(company=company, id=payload["account_id"], is_group=False, is_active=True).first()
                if payload.get("account_id")
                else accounts["4150"]
            )
            counter_acc = FleetAccountResolver.resolve_counter_account(
                company,
                payment_method=payment_method,
                party=party,
                explicit_account_id=payload.get("counter_account_id"),
            )
            voucher_type = (
                Voucher.VoucherType.SALES
                if payment_method == "CREDIT"
                else Voucher.VoucherType.RECEIPT
            )
            lines = [
                {
                    "account": counter_acc,
                    "debit": amount,
                    "credit": Decimal("0.00"),
                    "party": party if counter_acc.requires_subledger else None,
                    "description": payload.get("narration") or f"Vehicle income ({vehicle.registration_number})",
                },
                {
                    "account": inc_acc,
                    "debit": Decimal("0.00"),
                    "credit": amount,
                    "party": None,
                    "description": payload.get("narration") or f"Hire income ({vehicle.registration_number})",
                },
            ]
        else:
            if party and party.party_type not in ("SUPPLIER", "SUBCONTRACTOR", "BOTH"):
                raise ValueError("Vehicle Expense requires a SUPPLIER / SUBCONTRACTOR party.")
            default_exp = accounts["5310"] if vehicle.ownership_type == Vehicle.OwnershipType.RENTED_IN else accounts["5330"]
            exp_acc = (
                Account.objects.filter(company=company, id=payload["account_id"], is_group=False, is_active=True).first()
                if payload.get("account_id")
                else default_exp
            )
            counter_acc = FleetAccountResolver.resolve_counter_account(
                company,
                payment_method=payment_method,
                party=party,
                explicit_account_id=payload.get("counter_account_id"),
            )
            voucher_type = (
                Voucher.VoucherType.EQUIPMENT_HIRE
                if payment_method == "CREDIT"
                else Voucher.VoucherType.PAYMENT
            )
            lines = [
                {
                    "account": exp_acc,
                    "debit": amount,
                    "credit": Decimal("0.00"),
                    "party": None,
                    "description": payload.get("narration") or f"Vehicle expense ({vehicle.registration_number})",
                },
                {
                    "account": counter_acc,
                    "debit": Decimal("0.00"),
                    "credit": amount,
                    "party": party if counter_acc.requires_subledger else None,
                    "description": payload.get("narration") or f"Vehicle payable/payment ({vehicle.registration_number})",
                },
            ]

        proj = Project.objects.filter(company=company, id=payload["project_id"]).first() if payload.get("project_id") else vehicle.assigned_project
        v_date = payload.get("transaction_date") or date.today()
        if isinstance(v_date, str):
            v_date = date.fromisoformat(v_date)

        plan = PostingRuleEngine.build_voucher_accounting_plan(
            company=company,
            voucher_type=voucher_type,
            voucher_date=v_date,
            lines_data=[{**l, "project": proj} for l in lines],
            party=party if any(l["account"].requires_subledger for l in lines) else None,
        )
        return {
            "voucher_type": voucher_type,
            "entry_mode": entry_mode,
            "payment_method": payment_method,
            "vehicle": vehicle,
            "party": party,
            "project": proj,
            "transaction_date": v_date,
            "amount": amount,
            "lines": lines,
            "plan": plan,
        }


class VehicleCashEntryService:
    """Handles quick Single-Entry Cash or Bank Income & Expense WITHOUT any Customer/Supplier party."""

    @staticmethod
    @transaction.atomic
    def record_single_entry_income(*, company: Company, actor, data: dict) -> VehicleIncome:
        idem = (data.get("idempotency_key") or "").strip() or None
        if idem:
            ex = VehicleIncome.objects.filter(company=company, idempotency_key=idem).first()
            if ex:
                return ex

        built = VehicleAccountingPostingService.build_preview(
            company=company,
            payload={**data, "transaction_kind": "INCOME", "entry_mode": "SINGLE_ENTRY"},
        )
        if not built["plan"]["is_valid"]:
            raise ValueError(built["plan"]["validation_errors"])

        vehicle = built["vehicle"]
        trip = VehicleTrip.objects.filter(company=company, id=data["trip_id"]).first() if data.get("trip_id") else None
        agr = VehicleRentalAgreement.objects.filter(company=company, id=data["rental_agreement_id"]).first() if data.get("rental_agreement_id") else None

        voucher = VoucherService.create_draft(
            company=company,
            user=actor,
            data={
                "voucher_type": built["voucher_type"],
                "voucher_date": built["transaction_date"],
                "project": built["project"],
                "site": vehicle.assigned_site,
                "branch": vehicle.branch,
                "reference_no": data.get("payment_reference") or (trip.trip_number if trip else ""),
                "narration": data.get("narration") or f"Single Entry Cash/Bank Income — {vehicle.registration_number}",
                "gross_amount": built["amount"],
                "net_amount": built["amount"],
                "entry_mode": "DOUBLE_ENTRY",
            },
            lines_data=built["lines"],
        )
        voucher = _finalize_voucher(company, voucher, actor, post_now=bool(data.get("post_now", True)))

        inc = VehicleIncome.objects.create(
            company=company,
            branch=vehicle.branch,
            fiscal_year=voucher.fiscal_year,
            vehicle=vehicle,
            trip=trip,
            rental_agreement=agr,
            project=built["project"],
            site=vehicle.assigned_site,
            transaction_date=built["transaction_date"],
            entry_mode="SINGLE_ENTRY",
            payment_method=built["payment_method"],
            income_category=data.get("income_category") or VehicleIncome.Category.VEHICLE_HIRE,
            party=None,  # Strictly NO party created
            counter_account=built["lines"][0]["account"],
            income_account=built["lines"][1]["account"],
            gross_amount=built["amount"],
            net_amount=built["amount"],
            payment_reference=data.get("payment_reference", ""),
            narration=data.get("narration", ""),
            voucher=voucher,
            idempotency_key=idem,
            entered_by=actor,
        )
        record_fleet_audit(company=company, actor=actor, vehicle=vehicle, action="SINGLE_ENTRY_INCOME", entity_type="VehicleIncome", entity_id=str(inc.id))
        return inc

    @staticmethod
    @transaction.atomic
    def record_single_entry_expense(*, company: Company, actor, data: dict) -> VehicleExpense:
        idem = (data.get("idempotency_key") or "").strip() or None
        if idem:
            ex = VehicleExpense.objects.filter(company=company, idempotency_key=idem).first()
            if ex:
                return ex

        built = VehicleAccountingPostingService.build_preview(
            company=company,
            payload={**data, "transaction_kind": "EXPENSE", "entry_mode": "SINGLE_ENTRY"},
        )
        if not built["plan"]["is_valid"]:
            raise ValueError(built["plan"]["validation_errors"])

        vehicle = built["vehicle"]
        trip = VehicleTrip.objects.filter(company=company, id=data["trip_id"]).first() if data.get("trip_id") else None
        cc = CostCenter.objects.filter(company=company, id=data["cost_center_id"]).first() if data.get("cost_center_id") else vehicle.assigned_cost_center

        voucher = VoucherService.create_draft(
            company=company,
            user=actor,
            data={
                "voucher_type": built["voucher_type"],
                "voucher_date": built["transaction_date"],
                "project": built["project"],
                "site": vehicle.assigned_site,
                "branch": vehicle.branch,
                "cost_center": cc,
                "narration": data.get("narration") or f"Single Entry Cash/Bank Expense — {vehicle.registration_number}",
                "gross_amount": built["amount"],
                "net_amount": built["amount"],
            },
            lines_data=built["lines"],
        )
        voucher = _finalize_voucher(company, voucher, actor, post_now=bool(data.get("post_now", True)))

        exp = VehicleExpense.objects.create(
            company=company,
            branch=vehicle.branch,
            fiscal_year=voucher.fiscal_year,
            vehicle=vehicle,
            trip=trip,
            project=built["project"],
            site=vehicle.assigned_site,
            cost_center=cc,
            transaction_date=built["transaction_date"],
            entry_mode="SINGLE_ENTRY",
            payment_method=built["payment_method"],
            expense_category=data.get("expense_category") or VehicleExpense.Category.REPAIR_MAINT,
            party=None,  # Strictly NO supplier party
            expense_account=built["lines"][0]["account"],
            counter_account=built["lines"][1]["account"],
            gross_amount=built["amount"],
            net_amount=built["amount"],
            narration=data.get("narration", ""),
            voucher=voucher,
            idempotency_key=idem,
            entered_by=actor,
        )
        record_fleet_audit(company=company, actor=actor, vehicle=vehicle, action="SINGLE_ENTRY_EXPENSE", entity_type="VehicleExpense", entity_id=str(exp.id))
        return exp


class VehiclePartyBillingService:
    """Double-Entry Customer & Supplier accounting, Receipts/Payments, and Security Deposits."""

    @staticmethod
    @transaction.atomic
    def record_double_entry_income(*, company: Company, actor, data: dict) -> VehicleIncome:
        built = VehicleAccountingPostingService.build_preview(
            company=company,
            payload={**data, "transaction_kind": "INCOME", "entry_mode": "DOUBLE_ENTRY"},
        )
        if not built["plan"]["is_valid"]:
            raise ValueError(built["plan"]["validation_errors"])

        vehicle = built["vehicle"]
        party = built["party"]
        inv_no = (data.get("invoice_number") or "").strip() or f"VINV-{VehicleCustomerBilling.objects.filter(company=company).count() + 1:05d}"
        if built["payment_method"] == "CREDIT" and VehicleCustomerBilling.objects.filter(company=company, invoice_no=inv_no).exists():
            raise ValueError(f"Duplicate customer invoice number '{inv_no}'.")

        voucher = VoucherService.create_draft(
            company=company,
            user=actor,
            data={
                "voucher_type": built["voucher_type"],
                "voucher_date": built["transaction_date"],
                "project": built["project"],
                "party": party,
                "reference_no": inv_no,
                "narration": data.get("narration") or f"Customer Vehicle Hire Invoice {inv_no} — {vehicle.registration_number}",
                "gross_amount": built["amount"],
                "net_amount": built["amount"],
            },
            lines_data=built["lines"],
        )
        voucher = _finalize_voucher(company, voucher, actor, post_now=bool(data.get("post_now", True)))

        inc = VehicleIncome.objects.create(
            company=company,
            branch=vehicle.branch,
            fiscal_year=voucher.fiscal_year,
            vehicle=vehicle,
            project=built["project"],
            transaction_date=built["transaction_date"],
            entry_mode="DOUBLE_ENTRY",
            payment_method=built["payment_method"],
            income_category=data.get("income_category") or VehicleIncome.Category.VEHICLE_HIRE,
            party=party,
            counter_account=built["lines"][0]["account"],
            income_account=built["lines"][1]["account"],
            gross_amount=built["amount"],
            net_amount=built["amount"],
            invoice_number=inv_no,
            narration=data.get("narration", ""),
            voucher=voucher,
            entered_by=actor,
        )
        if built["payment_method"] == "CREDIT":
            VehicleCustomerBilling.objects.create(
                company=company,
                vehicle_income=inc,
                party=party,
                invoice_no=inv_no,
                total_amount=built["amount"],
            )
        return inc

    @staticmethod
    @transaction.atomic
    def record_double_entry_expense(*, company: Company, actor, data: dict) -> VehicleExpense:
        built = VehicleAccountingPostingService.build_preview(
            company=company,
            payload={**data, "transaction_kind": "EXPENSE", "entry_mode": "DOUBLE_ENTRY"},
        )
        if not built["plan"]["is_valid"]:
            raise ValueError(built["plan"]["validation_errors"])

        vehicle = built["vehicle"]
        party = built["party"]
        sup_inv = (data.get("supplier_invoice_no") or "").strip() or f"VRB-{VehicleSupplierBilling.objects.filter(company=company).count() + 1:05d}"
        if built["payment_method"] == "CREDIT" and VehicleSupplierBilling.objects.filter(company=company, party=party, supplier_invoice_no=sup_inv).exists():
            raise ValueError(f"Duplicate supplier invoice '{sup_inv}' for {party.name}.")

        agr = VehicleRentalAgreement.objects.filter(company=company, id=data["rental_agreement_id"]).first() if data.get("rental_agreement_id") else None
        cc = CostCenter.objects.filter(company=company, id=data["cost_center_id"]).first() if data.get("cost_center_id") else vehicle.assigned_cost_center
        cost_code = CostCode.objects.filter(id=data["cost_code_id"]).first() if data.get("cost_code_id") else None

        voucher = VoucherService.create_draft(
            company=company,
            user=actor,
            data={
                "voucher_type": built["voucher_type"],
                "voucher_date": built["transaction_date"],
                "project": built["project"],
                "cost_center": cc,
                "party": party,
                "supplier_invoice_no": sup_inv,
                "narration": data.get("narration") or f"Supplier Vehicle Rental Bill {sup_inv} — {vehicle.registration_number}",
                "gross_amount": built["amount"],
                "net_amount": built["amount"],
            },
            lines_data=built["lines"],
        )
        voucher = _finalize_voucher(company, voucher, actor, post_now=bool(data.get("post_now", True)))

        exp = VehicleExpense.objects.create(
            company=company,
            branch=vehicle.branch,
            fiscal_year=voucher.fiscal_year,
            vehicle=vehicle,
            rental_agreement=agr,
            project=built["project"],
            cost_center=cc,
            cost_code=cost_code,
            transaction_date=built["transaction_date"],
            entry_mode="DOUBLE_ENTRY",
            payment_method=built["payment_method"],
            expense_category=data.get("expense_category") or VehicleExpense.Category.VEHICLE_HIRE,
            hire_basis=data.get("hire_basis") or (agr.rate_type if agr else "DAILY"),
            quantity=Decimal(str(data.get("quantity") or "1.000")),
            rate=Decimal(str(data.get("rate") or built["amount"])),
            party=party,
            expense_account=built["lines"][0]["account"],
            counter_account=built["lines"][1]["account"],
            gross_amount=built["amount"],
            net_amount=built["amount"],
            supplier_invoice_no=sup_inv,
            narration=data.get("narration", ""),
            voucher=voucher,
            entered_by=actor,
        )
        if built["payment_method"] == "CREDIT":
            VehicleSupplierBilling.objects.create(
                company=company,
                vehicle_expense=exp,
                party=party,
                supplier_invoice_no=sup_inv,
                total_amount=built["amount"],
            )
        return exp

    @staticmethod
    @transaction.atomic
    def settle_party_billing(*, company: Company, actor, direction: str, billing_id: str, amount: Decimal, payment_method: str = "BANK", txn_date=None) -> dict:
        """Handles Customer Receipt (AR) or Supplier Payment (AP) and allocates directly against central OpenItem."""
        amt = Decimal(str(amount)).quantize(Decimal("0.01"))
        if amt <= 0:
            raise ValueError("Settlement amount must exceed zero.")
        accounts = FleetAccountResolver.ensure_fleet_accounts(company)
        cb_acc = FleetAccountResolver.resolve_counter_account(company, payment_method=payment_method)
        dt = txn_date or date.today()
        if isinstance(dt, str):
            dt = date.fromisoformat(dt)

        if direction == "CUSTOMER_RECEIPT":
            bill = VehicleCustomerBilling.objects.select_for_update().select_related("vehicle_income__voucher", "party").get(company=company, id=billing_id)
            remaining = bill.total_amount - bill.received_amount
            if amt > remaining:
                raise ValueError(f"Receipt amount ({amt}) exceeds open invoice balance ({remaining}).")
            debtors_acc = Account.objects.filter(company=company, control_role=Account.ControlRole.SUNDRY_DEBTORS, is_group=False).first() or accounts["1110"]
            v = VoucherService.create_draft(
                company=company,
                user=actor,
                data={"voucher_type": Voucher.VoucherType.RECEIPT, "voucher_date": dt, "party": bill.party, "narration": f"Receipt against {bill.invoice_no}"},
                lines_data=[
                    {"account": cb_acc, "debit": amt, "credit": Decimal("0.00"), "party": None},
                    {"account": debtors_acc, "debit": Decimal("0.00"), "credit": amt, "party": bill.party},
                ],
            )
            v = _finalize_voucher(company, v, actor, post_now=True)
            oi = OpenItem.objects.get(company=company, voucher=bill.vehicle_income.voucher, is_unallocated_credit=False)
            InvoiceAllocationService.allocate_batch(
                company=company,
                user=actor,
                party=bill.party,
                settlement_voucher=v,
                allocations=[{"open_item_id": oi.id, "allocated_amount": str(amt)}],
                hub_side=OpenItem.HubSide.RECEIVABLE,
            )
            bill.received_amount += amt
            bill.status = "SETTLED" if bill.received_amount >= bill.total_amount else "PARTIAL"
            bill.save(update_fields=["received_amount", "status"])
            return {"status": bill.status, "received_amount": str(bill.received_amount), "voucher_no": v.voucher_no}

        bill = VehicleSupplierBilling.objects.select_for_update().select_related("vehicle_expense__voucher", "party").get(company=company, id=billing_id)
        remaining = bill.total_amount - bill.paid_amount
        if amt > remaining:
            raise ValueError(f"Payment amount ({amt}) exceeds open payable ({remaining}).")
        cred_acc = Account.objects.filter(company=company, control_role=Account.ControlRole.SUNDRY_CREDITORS, is_group=False).first() or accounts["2010"]
        v = VoucherService.create_draft(
            company=company,
            user=actor,
            data={"voucher_type": Voucher.VoucherType.PAYMENT, "voucher_date": dt, "party": bill.party, "narration": f"Payment against {bill.supplier_invoice_no}"},
            lines_data=[
                {"account": cred_acc, "debit": amt, "credit": Decimal("0.00"), "party": bill.party},
                {"account": cb_acc, "debit": Decimal("0.00"), "credit": amt, "party": None},
            ],
        )
        v = _finalize_voucher(company, v, actor, post_now=True)
        oi = OpenItem.objects.get(company=company, voucher=bill.vehicle_expense.voucher, is_unallocated_credit=False)
        InvoiceAllocationService.allocate_batch(
            company=company,
            user=actor,
            party=bill.party,
            settlement_voucher=v,
            allocations=[{"open_item_id": oi.id, "allocated_amount": str(amt)}],
            hub_side=OpenItem.HubSide.PAYABLE,
        )
        bill.paid_amount += amt
        bill.status = "SETTLED" if bill.paid_amount >= bill.total_amount else "PARTIAL"
        bill.save(update_fields=["paid_amount", "status"])
        return {"status": bill.status, "paid_amount": str(bill.paid_amount), "voucher_no": v.voucher_no}

    @staticmethod
    @transaction.atomic
    def record_security_deposit(*, company: Company, actor, data: dict) -> VehicleSecurityDeposit:
        vehicle = Vehicle.objects.get(company=company, id=data["vehicle_id"])
        party = Party.objects.get(company=company, id=data["party_id"])
        direction = data["direction"]
        amt = Decimal(str(data["amount"])).quantize(Decimal("0.01"))
        if amt <= 0:
            raise ValueError("Deposit amount must exceed zero.")
        accounts = FleetAccountResolver.ensure_fleet_accounts(company)
        cb_acc = FleetAccountResolver.resolve_counter_account(company, payment_method=data.get("payment_method", "BANK"))
        dt = data.get("deposit_date") or date.today()
        if isinstance(dt, str):
            dt = date.fromisoformat(dt)

        if direction == VehicleSecurityDeposit.Direction.PAID_TO_OWNER:
            dep_acc = accounts["1350"]
            lines = [
                {"account": dep_acc, "debit": amt, "credit": Decimal("0.00")},
                {"account": cb_acc, "debit": Decimal("0.00"), "credit": amt},
            ]
            vtype = Voucher.VoucherType.PAYMENT
        else:
            dep_acc = accounts["2250"]
            lines = [
                {"account": cb_acc, "debit": amt, "credit": Decimal("0.00")},
                {"account": dep_acc, "debit": Decimal("0.00"), "credit": amt},
            ]
            vtype = Voucher.VoucherType.RECEIPT

        v = VoucherService.create_draft(
            company=company,
            user=actor,
            data={"voucher_type": vtype, "voucher_date": dt, "narration": f"Vehicle Security Deposit ({direction}) — {vehicle.registration_number}"},
            lines_data=lines,
        )
        v = _finalize_voucher(company, v, actor, post_now=True)

        return VehicleSecurityDeposit.objects.create(
            company=company,
            direction=direction,
            vehicle=vehicle,
            party=party,
            deposit_date=dt,
            amount=amt,
            deposit_account=dep_acc,
            cash_bank_account=cb_acc,
            voucher=v,
        )

    @staticmethod
    @transaction.atomic
    def refund_security_deposit(*, company: Company, deposit: VehicleSecurityDeposit, actor, refund_amount: Decimal | None = None) -> VehicleSecurityDeposit:
        dep = VehicleSecurityDeposit.objects.select_for_update().get(id=deposit.id)
        amt = Decimal(str(refund_amount or (dep.amount - dep.refunded_amount))).quantize(Decimal("0.01"))
        if amt <= 0 or amt > (dep.amount - dep.refunded_amount):
            raise ValueError("Invalid deposit refund amount.")
        if dep.direction == VehicleSecurityDeposit.Direction.PAID_TO_OWNER:
            lines = [
                {"account": dep.cash_bank_account, "debit": amt, "credit": Decimal("0.00")},
                {"account": dep.deposit_account, "debit": Decimal("0.00"), "credit": amt},
            ]
            vtype = Voucher.VoucherType.RECEIPT
        else:
            lines = [
                {"account": dep.deposit_account, "debit": amt, "credit": Decimal("0.00")},
                {"account": dep.cash_bank_account, "debit": Decimal("0.00"), "credit": amt},
            ]
            vtype = Voucher.VoucherType.PAYMENT

        v = VoucherService.create_draft(
            company=company,
            user=actor,
            data={"voucher_type": vtype, "voucher_date": date.today(), "narration": f"Security Deposit Refund — {dep.vehicle.registration_number}"},
            lines_data=lines,
        )
        v = _finalize_voucher(company, v, actor, post_now=True)
        dep.refunded_amount += amt
        dep.refund_voucher = v
        dep.status = "REFUNDED" if dep.refunded_amount >= dep.amount else "PARTIAL_REFUND"
        dep.save()
        return dep



class VehicleTransactionReversalService:
    """Audit-safe reversal of posted Fleet Income & Expense transactions via PostingService."""

    @staticmethod
    @transaction.atomic
    def reverse_transaction(*, company: Company, kind: str, record_id: str, actor, reason: str) -> dict:
        if not actor.is_superuser:
            mem = CompanyMembership.objects.filter(user=actor, company=company, is_active=True).first()
            perms = set(mem.effective_permissions()) if mem else set()
            if Permissions.VEHICLE_REVERSE not in perms and Permissions.VOUCHER_REVERSE not in perms:
                raise PermissionError("You do not have permission to reverse fleet transactions.")

        kind_u = (kind or "").upper()
        if kind_u == "INCOME":
            rec = VehicleIncome.objects.select_for_update().get(company=company, id=record_id)
        elif kind_u == "EXPENSE":
            rec = VehicleExpense.objects.select_for_update().get(company=company, id=record_id)
        else:
            raise ValueError("kind must be INCOME or EXPENSE.")

        if rec.is_reversed:
            raise ValueError("This fleet transaction has already been reversed.")

        rev_voucher = None
        if rec.voucher_id:
            v = rec.voucher
            if v.status == Voucher.Status.POSTED:
                rev_voucher = PostingService.reverse_voucher(
                    voucher=v,
                    user=actor,
                    reversal_date=date.today(),
                    reason=reason or f"Fleet {kind_u} reversal",
                )
            elif v.status in (Voucher.Status.DRAFT, Voucher.Status.SUBMITTED, Voucher.Status.APPROVED):
                v.status = Voucher.Status.CANCELLED
                v.save(update_fields=["status"])

        rec.is_reversed = True
        rec.reversal_reason = (reason or "Reversed")[:255]
        rec.reversed_voucher = rev_voucher
        rec.save(update_fields=["is_reversed", "reversal_reason", "reversed_voucher"])

        if kind_u == "INCOME" and hasattr(rec, "customer_billing"):
            cb = rec.customer_billing
            if cb.received_amount == 0:
                cb.status = "REVERSED"
                cb.save(update_fields=["status"])
        elif kind_u == "EXPENSE" and hasattr(rec, "supplier_billing"):
            sb = rec.supplier_billing
            if sb.paid_amount == 0:
                sb.status = "REVERSED"
                sb.save(update_fields=["status"])

        record_fleet_audit(
            company=company,
            actor=actor,
            vehicle=rec.vehicle,
            action=f"{kind_u}_REVERSED",
            entity_type=f"Vehicle{kind_u.title()}",
            entity_id=str(rec.id),
            metadata={"reason": rec.reversal_reason, "reversed_voucher_id": str(rev_voucher.id) if rev_voucher else None},
        )
        return {
            "id": str(rec.id),
            "kind": kind_u,
            "is_reversed": True,
            "reversed_voucher_id": str(rev_voucher.id) if rev_voucher else None,
        }


class VehicleAdvanceSettlementService:
    """Driver & Party Advance issuance and balanced GL expense/refund settlement."""

    @staticmethod
    @transaction.atomic
    def issue_advance(*, company: Company, actor, data: dict) -> VehicleAdvance:
        from apps.fleet.models import VehicleDriver

        kind = (data.get("kind") or VehicleAdvance.Kind.DRIVER_ADVANCE).upper()
        amount = Decimal(str(data.get("amount") or "0.00")).quantize(Decimal("0.01"))
        if amount <= 0:
            raise ValueError("Advance amount must exceed zero.")

        adv_date = data.get("advance_date") or date.today()
        if isinstance(adv_date, str):
            adv_date = date.fromisoformat(adv_date)

        vehicle = Vehicle.objects.filter(company=company, id=data["vehicle_id"]).first() if data.get("vehicle_id") else None
        driver = VehicleDriver.objects.filter(company=company, id=data["driver_id"]).first() if data.get("driver_id") else None
        agr = VehicleRentalAgreement.objects.filter(company=company, id=data["rental_agreement_id"]).first() if data.get("rental_agreement_id") else None
        party = Party.objects.filter(company=company, id=data["party_id"]).first() if data.get("party_id") else None

        if kind in (VehicleAdvance.Kind.DRIVER_ADVANCE, VehicleAdvance.Kind.FUEL_ADVANCE) and not driver:
            raise ValueError("Driver or Fuel Advance requires selecting a Driver.")
        if kind in (VehicleAdvance.Kind.RENTAL_SUPPLIER_ADV, VehicleAdvance.Kind.CUSTOMER_HIRE_ADV) and not party:
            raise ValueError("Customer/Supplier Advance requires selecting a Party.")

        accounts = FleetAccountResolver.ensure_fleet_accounts(company)
        pay_method = (data.get("payment_method") or "CASH").upper()
        cash_bank = FleetAccountResolver.resolve_counter_account(
            company,
            payment_method=pay_method if pay_method in ("CASH", "BANK") else "CASH",
            party=None,
            explicit_account_id=data.get("counter_account_id"),
        )

        if kind == VehicleAdvance.Kind.CUSTOMER_HIRE_ADV:
            adv_acc = accounts["2070"]
            vtype = Voucher.VoucherType.RECEIPT
            lines = [
                {"account": cash_bank, "debit": amount, "credit": Decimal("0.00"), "description": "Customer vehicle hire advance received"},
                {"account": adv_acc, "debit": Decimal("0.00"), "credit": amount, "party": party if adv_acc.requires_subledger else None, "description": data.get("notes") or f"Advance from {party.name}"},
            ]
        else:
            adv_acc = accounts["1185"] if kind == VehicleAdvance.Kind.RENTAL_SUPPLIER_ADV else accounts["1170"]
            vtype = Voucher.VoucherType.PAYMENT
            lines = [
                {"account": adv_acc, "debit": amount, "credit": Decimal("0.00"), "party": party if (party and adv_acc.requires_subledger) else None, "description": data.get("notes") or f"Fleet {kind}"},
                {"account": cash_bank, "debit": Decimal("0.00"), "credit": amount, "description": f"Disbursed {kind}"},
            ]

        voucher = VoucherService.create_draft(
            company=company,
            user=actor,
            data={
                "voucher_type": vtype,
                "voucher_date": adv_date,
                "project": vehicle.assigned_project if vehicle else None,
                "party": party,
                "narration": data.get("notes") or f"Fleet Advance ({kind})",
                "gross_amount": amount,
                "net_amount": amount,
            },
            lines_data=lines,
        )
        voucher = _finalize_voucher(company, voucher, actor, post_now=bool(data.get("post_now", True)))

        adv = VehicleAdvance.objects.create(
            company=company,
            vehicle=vehicle,
            rental_agreement=agr,
            driver=driver,
            party=party,
            kind=kind,
            advance_date=adv_date,
            amount=amount,
            voucher=voucher,
            notes=data.get("notes", ""),
        )
        record_fleet_audit(
            company=company,
            actor=actor,
            vehicle=vehicle,
            action="ADVANCE_ISSUED",
            entity_type="VehicleAdvance",
            entity_id=str(adv.id),
            metadata={"kind": kind, "amount": str(amount)},
        )
        return adv

    @staticmethod
    @transaction.atomic
    def settle_driver_advance(*, company: Company, actor, advance_id: str, data: dict):
        from apps.fleet.models import VehicleDriverSettlement

        adv = VehicleAdvance.objects.select_for_update().get(company=company, id=advance_id)
        if not adv.driver_id:
            raise ValueError("Selected advance is not a Driver/Fuel Advance.")

        fuel_exp = Decimal(str(data.get("fuel_expense") or "0.00")).quantize(Decimal("0.01"))
        trip_exp = Decimal(str(data.get("trip_expense") or "0.00")).quantize(Decimal("0.01"))
        toll_exp = Decimal(str(data.get("road_toll_expense") or "0.00")).quantize(Decimal("0.01"))
        allow_exp = Decimal(str(data.get("allowance_expense") or "0.00")).quantize(Decimal("0.01"))
        maint_exp = Decimal(str(data.get("maintenance_expense") or "0.00")).quantize(Decimal("0.01"))
        cash_ret = Decimal(str(data.get("cash_returned") or "0.00")).quantize(Decimal("0.01"))

        total_exp = (fuel_exp + trip_exp + toll_exp + allow_exp + maint_exp).quantize(Decimal("0.01"))
        total_settled = (total_exp + cash_ret).quantize(Decimal("0.01"))
        remaining = (adv.amount - adv.settled_amount).quantize(Decimal("0.01"))
        if total_settled <= 0:
            raise ValueError("Settlement expense + cash return must exceed zero.")
        if total_settled > remaining:
            raise ValueError(f"Settlement total ({total_settled}) exceeds remaining driver advance balance ({remaining}).")

        sdate = data.get("settlement_date") or date.today()
        if isinstance(sdate, str):
            sdate = date.fromisoformat(sdate)

        vehicle = Vehicle.objects.filter(company=company, id=data["vehicle_id"]).first() if data.get("vehicle_id") else adv.vehicle
        accounts = FleetAccountResolver.ensure_fleet_accounts(company)
        lines = []
        if fuel_exp > 0:
            lines.append({"account": accounts["5320"], "debit": fuel_exp, "credit": Decimal("0.00"), "description": "Driver settled fuel expense"})
        ops_exp = (trip_exp + toll_exp + allow_exp).quantize(Decimal("0.01"))
        if ops_exp > 0:
            lines.append({"account": accounts["5310"], "debit": ops_exp, "credit": Decimal("0.00"), "description": "Driver trip/toll/allowance expense"})
        if maint_exp > 0:
            lines.append({"account": accounts["5330"], "debit": maint_exp, "credit": Decimal("0.00"), "description": "Driver settled minor repair"})
        if cash_ret > 0:
            cash_acc = FleetAccountResolver.resolve_counter_account(
                company,
                payment_method="CASH",
                party=None,
                explicit_account_id=data.get("counter_account_id"),
            )
            lines.append({"account": cash_acc, "debit": cash_ret, "credit": Decimal("0.00"), "description": "Cash returned by driver"})

        lines.append({
            "account": accounts["1170"],
            "debit": Decimal("0.00"),
            "credit": total_settled,
            "description": f"Settlement of advance for {adv.driver.full_name}",
        })

        voucher = VoucherService.create_draft(
            company=company,
            user=actor,
            data={
                "voucher_type": Voucher.VoucherType.JOURNAL,
                "voucher_date": sdate,
                "project": vehicle.assigned_project if vehicle else None,
                "narration": data.get("notes") or f"Driver Advance Settlement — {adv.driver.full_name}",
                "gross_amount": total_settled,
                "net_amount": total_settled,
            },
            lines_data=lines,
        )
        voucher = _finalize_voucher(company, voucher, actor, post_now=True)

        adv.settled_amount = (adv.settled_amount + total_settled).quantize(Decimal("0.01"))
        adv.save(update_fields=["settled_amount"])

        settlement = VehicleDriverSettlement.objects.create(
            company=company,
            advance=adv,
            driver=adv.driver,
            vehicle=vehicle,
            settlement_date=sdate,
            fuel_expense=fuel_exp,
            trip_expense=trip_exp,
            road_toll_expense=toll_exp,
            allowance_expense=allow_exp,
            maintenance_expense=maint_exp,
            total_expensed=total_exp,
            cash_returned=cash_ret,
            voucher=voucher,
            notes=data.get("notes", ""),
            settled_by=actor,
        )
        record_fleet_audit(
            company=company,
            actor=actor,
            vehicle=vehicle,
            action="DRIVER_ADVANCE_SETTLED",
            entity_type="VehicleDriverSettlement",
            entity_id=str(settlement.id),
            metadata={"total_expensed": str(total_exp), "cash_returned": str(cash_ret)},
        )
        return settlement


class FleetOfflineSyncService:
    """Idempotent offline-first sync queue for Trips, Fuel, Maintenance & Cash Vouchers."""

    @staticmethod
    def sync_batch(*, company: Company, actor, device_id: str, operations: list[dict]) -> list[dict]:
        from apps.fleet.services.rentals_and_trips import VehicleTripService
        from apps.fleet.services.fuel_maintenance_costing import VehicleFuelService, VehicleMaintenanceService

        results = []
        for op in operations or []:
            cuuid = str(op.get("client_uuid") or "")
            op_type = (op.get("operation_type") or op.get("kind") or "").upper()
            payload = dict(op.get("payload") or {})
            try:
                if op_type == "TRIP":
                    t = VehicleTripService.create_trip(company=company, actor=actor, data=payload)
                    results.append({"client_uuid": cuuid, "status": "SYNCED", "server_id": str(t.id), "error": ""})
                elif op_type == "FUEL":
                    f = VehicleFuelService.record_fuel(company=company, actor=actor, data=payload)
                    results.append({"client_uuid": cuuid, "status": "SYNCED", "server_id": str(f.id), "error": ""})
                elif op_type == "MAINTENANCE":
                    m = VehicleMaintenanceService.record_maintenance(company=company, actor=actor, data=payload)
                    results.append({"client_uuid": cuuid, "status": "SYNCED", "server_id": str(m.id), "error": ""})
                elif op_type == "SINGLE_ENTRY_EXPENSE":
                    if cuuid and "idempotency_key" not in payload:
                        payload["idempotency_key"] = f"offline:{device_id}:{cuuid}"
                    e = VehicleCashEntryService.record_single_entry_expense(company=company, actor=actor, data=payload)
                    results.append({"client_uuid": cuuid, "status": "SYNCED", "server_id": str(e.id), "error": ""})
                elif op_type == "SINGLE_ENTRY_INCOME":
                    if cuuid and "idempotency_key" not in payload:
                        payload["idempotency_key"] = f"offline:{device_id}:{cuuid}"
                    i = VehicleCashEntryService.record_single_entry_income(company=company, actor=actor, data=payload)
                    results.append({"client_uuid": cuuid, "status": "SYNCED", "server_id": str(i.id), "error": ""})
                else:
                    results.append({"client_uuid": cuuid, "status": "FAILED", "server_id": None, "error": f"Unsupported offline operation '{op_type}'"})
            except Exception as exc:
                results.append({"client_uuid": cuuid, "status": "FAILED", "server_id": None, "error": str(exc)})
        return results
