import csv
import io
from datetime import date, timedelta
from decimal import Decimal, ROUND_HALF_UP
from typing import Any

from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import Sum
from django.utils import timezone

from apps.accounting.models import (
    Account,
    AdvanceRecord,
    FinancialYearOpeningCarryForward,
    LedgerEntry,
    OpeningBalanceAdjustmentMapping,
    OpeningBalanceApproval,
    OpeningBalanceAuditEvent,
    OpeningBalanceCorrection,
    OpeningBalanceImport,
    OpeningBalanceImportLine,
    OpeningBalanceLine,
    OpeningBalancePartyReference,
    OpeningBalanceProfile,
    OpeningBalanceReconciliation,
    OpeningBalanceSubledgerItem,
    OpeningBalanceVoucher,
    OpeningCategory,
    DirectionChoice,
    Party,
    Voucher,
)
from apps.accounts_rbac.constants import Permissions
from apps.accounts_rbac.models import CompanyMembership
from apps.audit.services import record_audit_event
from apps.banking.models import BankAccount, BankReconciliationSession, CashAccount
from apps.localization.bs_calendar import ad_to_bs, bs_to_ad
from apps.party_hub.models import OpenItem, RetentionSchedule
from apps.tenancy.models import FiscalPeriod, FiscalYear

from .core import PostingService, VoucherService

Q2 = Decimal("0.01")
Q6 = Decimal("0.000001")


def _q2(val: Any) -> Decimal:
    return Decimal(str(val or "0.00")).quantize(Q2, rounding=ROUND_HALF_UP)


def _q6(val: Any) -> Decimal:
    return Decimal(str(val or "1.000000")).quantize(Q6, rounding=ROUND_HALF_UP)


def _has_perm(company, user, perm_code: str) -> bool:
    if not user or not getattr(user, "is_authenticated", False):
        return False
    if getattr(user, "is_superuser", False):
        return True
    mem = CompanyMembership.objects.filter(company=company, user=user, is_active=True).first()
    if not mem:
        return False
    return perm_code in set(mem.effective_permissions())


def _audit_ob(*, company, action: str, entity_type: str, entity_id: str, actor=None, prev=None, new=None, previous_state=None, new_state=None, notes: str = ""):
    prev_val = previous_state if previous_state is not None else prev
    new_val = new_state if new_state is not None else new
    OpeningBalanceAuditEvent.objects.create(
        company=company,
        action=action,
        entity_type=entity_type,
        entity_id=str(entity_id),
        actor=actor,
        previous_state=prev_val,
        new_state=new_val,
        notes=(notes or "")[:255],
    )
    record_audit_event(
        company=company,
        actor=actor,
        action=action,
        entity_type=entity_type,
        entity_id=str(entity_id),
        previous_state=prev_val,
        new_state=new_val,
    )


def _active_fiscal_year(company, as_of: date | None = None) -> FiscalYear:
    qs = FiscalYear.objects.filter(company=company).order_by("-start_date")
    if as_of:
        fy = qs.filter(start_date__lte=as_of, end_date__gte=as_of).first()
        if fy:
            return fy
    fy = qs.filter(is_closed=False).first() or qs.first()
    if fy:
        return fy
    today = as_of or timezone.localdate()
    fy = FiscalYear.objects.create(
        company=company,
        name=f"{today.year}/{(today.year + 1) % 100:02d}",
        start_date=date(today.year, 1, 1),
        end_date=date(today.year, 12, 31),
        is_closed=False,
    )
    FiscalPeriod.objects.create(
        fiscal_year=fy,
        sequence=1,
        name="Period 1",
        start_date=fy.start_date,
        end_date=fy.end_date,
        status=FiscalPeriod.Status.OPEN,
    )
    return fy


def _next_ob_number(company) -> str:
    prefix = "OB-"
    existing = set(
        OpeningBalanceVoucher.objects.filter(company=company, ob_number__startswith=prefix).values_list("ob_number", flat=True)
    )
    idx = OpeningBalanceVoucher.objects.filter(company=company).count() + 1
    while f"{prefix}{idx:05d}" in existing:
        idx += 1
    return f"{prefix}{idx:05d}"


# ---------------------------------------------------------------------------
# 1. Direction Intelligence & Control Classification Service
# ---------------------------------------------------------------------------


class OpeningBalanceDirectionService:
    """Determines default Dr/Cr opening direction and guards opposite-direction party advances."""

    ROLE_DEFAULTS: dict[str, tuple[str, str, str]] = {
        Account.ControlRole.BANK: (DirectionChoice.DR, OpeningCategory.BANK, "Bank account balance is an asset (Debit normal)."),
        Account.ControlRole.CASH: (DirectionChoice.DR, OpeningCategory.CASH, "Cash vault / petty cash balance is an asset (Debit normal)."),
        Account.ControlRole.SUNDRY_DEBTORS: (DirectionChoice.DR, OpeningCategory.DEBTORS, "Customer receivable is a Debit asset."),
        Account.ControlRole.SUNDRY_CREDITORS: (DirectionChoice.CR, OpeningCategory.CREDITORS, "Supplier payable is a Credit liability."),
        Account.ControlRole.SUBCONTRACTOR_PAYABLE: (DirectionChoice.CR, OpeningCategory.CREDITORS, "Subcontractor payable is a Credit liability."),
        Account.ControlRole.RETENTION_RECEIVABLE: (DirectionChoice.DR, OpeningCategory.RETENTION_RECEIVABLE, "Client retention receivable is a Debit asset."),
        Account.ControlRole.RETENTION_PAYABLE: (DirectionChoice.CR, OpeningCategory.RETENTION_PAYABLE, "Subcontractor retention payable is a Credit liability."),
        Account.ControlRole.EMPLOYEE_ADVANCE: (DirectionChoice.DR, OpeningCategory.EMPLOYEE_ADVANCES, "Staff/Employee advance is a Debit asset."),
        Account.ControlRole.SUPPLIER_ADVANCE: (DirectionChoice.DR, OpeningCategory.SUPPLIER_ADVANCES, "Supplier advance paid is a Debit asset."),
        Account.ControlRole.CUSTOMER_ADVANCE: (DirectionChoice.CR, OpeningCategory.CUSTOMER_ADVANCES, "Customer mobilization/advance is a Credit liability."),
        Account.ControlRole.INVENTORY: (DirectionChoice.DR, OpeningCategory.INVENTORY, "Inventory stock on hand is a Debit asset."),
        Account.ControlRole.INPUT_VAT: (DirectionChoice.DR, OpeningCategory.TAX_RECEIVABLE, "Input VAT / TDS receivable is a Debit asset."),
        Account.ControlRole.TDS_RECEIVABLE: (DirectionChoice.DR, OpeningCategory.TAX_RECEIVABLE, "TDS advance receivable is a Debit asset."),
        Account.ControlRole.OUTPUT_VAT: (DirectionChoice.CR, OpeningCategory.TAX_PAYABLE, "Output VAT / TDS payable is a Credit liability."),
        Account.ControlRole.TDS_PAYABLE: (DirectionChoice.CR, OpeningCategory.TAX_PAYABLE, "TDS withholding payable is a Credit liability."),
        Account.ControlRole.ACCUM_DEPRECIATION: (DirectionChoice.CR, OpeningCategory.ACCUM_DEPRECIATION, "Accumulated depreciation is a Contra Asset (Credit normal)."),
        Account.ControlRole.BAD_DEBT_ALLOWANCE: (DirectionChoice.CR, OpeningCategory.OTHER, "Doubtful debt allowance is a Contra Asset (Credit normal)."),
        Account.ControlRole.EMPLOYEE_PAYABLE: (DirectionChoice.CR, OpeningCategory.OTHER, "Employee payable is a Credit liability."),
        Account.ControlRole.WAGES_PAYABLE: (DirectionChoice.CR, OpeningCategory.OTHER, "Wages payable is a Credit liability."),
        Account.ControlRole.PF_SSF_PAYABLE: (DirectionChoice.CR, OpeningCategory.TAX_PAYABLE, "Statutory PF/SSF payable is a Credit liability."),
        Account.ControlRole.EMPLOYEE_REIMBURSEMENT: (DirectionChoice.CR, OpeningCategory.OTHER, "Employee reimbursement is a Credit liability."),
        Account.ControlRole.STAFF_LOAN_RECEIVABLE: (DirectionChoice.DR, OpeningCategory.EMPLOYEE_ADVANCES, "Staff loan receivable is a Debit asset."),
    }

    PARTY_DEFAULTS: dict[str, tuple[str, str, str]] = {
        Party.PartyType.CUSTOMER: (DirectionChoice.DR, OpeningCategory.DEBTORS, "Customer opening receivable defaults to Debit (Dr)."),
        Party.PartyType.SUPPLIER: (DirectionChoice.CR, OpeningCategory.CREDITORS, "Supplier opening payable defaults to Credit (Cr)."),
        Party.PartyType.SUBCONTRACTOR: (DirectionChoice.CR, OpeningCategory.CREDITORS, "Subcontractor opening payable defaults to Credit (Cr)."),
        Party.PartyType.EMPLOYEE: (DirectionChoice.DR, OpeningCategory.EMPLOYEE_ADVANCES, "Employee advance defaults to Debit (Dr)."),
    }

    CATEGORY_DEFAULTS: dict[str, str] = {
        OpeningCategory.BANK: DirectionChoice.DR,
        OpeningCategory.CASH: DirectionChoice.DR,
        OpeningCategory.DEBTORS: DirectionChoice.DR,
        OpeningCategory.CREDITORS: DirectionChoice.CR,
        OpeningCategory.LOANS: DirectionChoice.CR,
        OpeningCategory.OD_CC: DirectionChoice.CR,
        OpeningCategory.FIXED_ASSETS: DirectionChoice.DR,
        OpeningCategory.ACCUM_DEPRECIATION: DirectionChoice.CR,
        OpeningCategory.INVENTORY: DirectionChoice.DR,
        OpeningCategory.EMPLOYEE_ADVANCES: DirectionChoice.DR,
        OpeningCategory.SUPPLIER_ADVANCES: DirectionChoice.DR,
        OpeningCategory.CUSTOMER_ADVANCES: DirectionChoice.CR,
        OpeningCategory.RETENTION_RECEIVABLE: DirectionChoice.DR,
        OpeningCategory.RETENTION_PAYABLE: DirectionChoice.CR,
        OpeningCategory.TAX_RECEIVABLE: DirectionChoice.DR,
        OpeningCategory.TAX_PAYABLE: DirectionChoice.CR,
        OpeningCategory.EQUITY: DirectionChoice.CR,
        OpeningCategory.OTHER: DirectionChoice.DR,
    }

    @classmethod
    def get_default_direction(
        cls,
        *,
        account: Account | None = None,
        party_type: str = "",
        category: str = "",
        entity_kind: str = "",
    ) -> dict[str, Any]:
        ek = (entity_kind or "").upper().strip()
        if ek in cls.CATEGORY_DEFAULTS:
            cat = ek
            return {
                "default_direction": cls.CATEGORY_DEFAULTS[cat],
                "opening_category": cat,
                "normal_balance": "DEBIT" if cls.CATEGORY_DEFAULTS[cat] == DirectionChoice.DR else "CREDIT",
                "explanation": f"Default opening direction for {cat.replace('_', ' ').title()}.",
            }
        if category and category in cls.CATEGORY_DEFAULTS and not account and not party_type:
            return {
                "default_direction": cls.CATEGORY_DEFAULTS[category],
                "opening_category": category,
                "normal_balance": "DEBIT" if cls.CATEGORY_DEFAULTS[category] == DirectionChoice.DR else "CREDIT",
                "explanation": f"Default opening direction for {category.replace('_', ' ').title()}.",
            }
        if party_type and party_type in cls.PARTY_DEFAULTS and not account:
            ddir, cat, exp = cls.PARTY_DEFAULTS[party_type]
            return {
                "default_direction": ddir,
                "opening_category": cat,
                "normal_balance": "DEBIT" if ddir == DirectionChoice.DR else "CREDIT",
                "explanation": exp,
            }
        if account:
            if account.control_role in cls.ROLE_DEFAULTS:
                ddir, cat, exp = cls.ROLE_DEFAULTS[account.control_role]
                return {
                    "default_direction": ddir,
                    "opening_category": category or cat,
                    "normal_balance": account.normal_balance,
                    "explanation": exp,
                }
            eff_class = account.effective_class
            if eff_class == Account.AccountClass.CONTRA_ASSET or account.control_role == Account.ControlRole.ACCUM_DEPRECIATION:
                return {
                    "default_direction": DirectionChoice.CR,
                    "opening_category": category or OpeningCategory.ACCUM_DEPRECIATION,
                    "normal_balance": "CREDIT",
                    "explanation": "Contra-Asset ledger defaults to Credit (Cr).",
                }
            if account.code.startswith("23") or account.code.startswith("22"):
                cat = OpeningCategory.OD_CC if ("OD" in account.name.upper() or "OVERDRAFT" in account.name.upper() or "CASH CREDIT" in account.name.upper()) else OpeningCategory.LOANS
                return {
                    "default_direction": DirectionChoice.CR,
                    "opening_category": category or cat,
                    "normal_balance": "CREDIT",
                    "explanation": "Loan / OD / Credit facility liability defaults to Credit (Cr).",
                }
            if account.code.startswith("15") and account.account_type == Account.AccountType.ASSET:
                return {
                    "default_direction": DirectionChoice.DR,
                    "opening_category": category or OpeningCategory.FIXED_ASSETS,
                    "normal_balance": "DEBIT",
                    "explanation": "Fixed Asset & Machinery ledger defaults to Debit (Dr).",
                }
            if account.account_type == Account.AccountType.EQUITY:
                return {
                    "default_direction": DirectionChoice.CR,
                    "opening_category": category or OpeningCategory.EQUITY,
                    "normal_balance": "CREDIT",
                    "explanation": "Capital & Equity account defaults to Credit (Cr).",
                }
            if account.account_type in (Account.AccountType.ASSET, Account.AccountType.EXPENSE):
                ddir = DirectionChoice.DR
                cat = category or OpeningCategory.OTHER
            else:
                ddir = DirectionChoice.CR
                cat = category or OpeningCategory.OTHER
            return {
                "default_direction": ddir,
                "opening_category": cat,
                "normal_balance": account.normal_balance,
                "explanation": f"{account.account_type.title()} account ({account.normal_balance} normal) defaults to {ddir}.",
            }
        ddir = cls.CATEGORY_DEFAULTS.get(category or OpeningCategory.OTHER, DirectionChoice.DR)
        return {
            "default_direction": ddir,
            "opening_category": category or OpeningCategory.OTHER,
            "normal_balance": "DEBIT" if ddir == DirectionChoice.DR else "CREDIT",
            "explanation": "Standard classification default.",
        }

    @classmethod
    def resolve_account_and_direction(
        cls,
        *,
        company,
        user=None,
        account: Account,
        party: Party | None = None,
        requested_direction: str = "",
        category: str = "",
        override_reason: str = "",
        reclassify_opposite_party: bool = True,
    ) -> dict[str, Any]:
        """Resolve effective GL control account and Dr/Cr direction, handling opposite party advances cleanly."""
        info = cls.get_default_direction(
            account=account,
            party_type=party.party_type if party else "",
            category=category,
        )
        default_dir = info["default_direction"]
        effective_dir = (requested_direction or default_dir).upper()
        if effective_dir not in (DirectionChoice.DR, DirectionChoice.CR):
            raise ValidationError(f"Invalid direction '{effective_dir}'; expected DR or CR.")

        effective_acc = account
        effective_cat = info["opening_category"]
        reclassified_to = ""
        is_overridden = effective_dir != default_dir

        if party and reclassify_opposite_party:
            if party.party_type == Party.PartyType.CUSTOMER and effective_dir == DirectionChoice.CR and account.control_role == Account.ControlRole.SUNDRY_DEBTORS:
                adv_acc = OpeningBalanceMappingService.find_or_create_control_account(company, Account.ControlRole.CUSTOMER_ADVANCE)
                effective_acc = adv_acc
                effective_cat = OpeningCategory.CUSTOMER_ADVANCES
                default_dir = DirectionChoice.CR
                is_overridden = False
                reclassified_to = f"Customer Credit reclassified to Customer Advance Liability ({adv_acc.code} — {adv_acc.name})"
            elif party.party_type in (Party.PartyType.SUPPLIER, Party.PartyType.SUBCONTRACTOR) and effective_dir == DirectionChoice.DR and account.control_role in (
                Account.ControlRole.SUNDRY_CREDITORS,
                Account.ControlRole.SUBCONTRACTOR_PAYABLE,
            ):
                adv_acc = OpeningBalanceMappingService.find_or_create_control_account(company, Account.ControlRole.SUPPLIER_ADVANCE)
                effective_acc = adv_acc
                effective_cat = OpeningCategory.SUPPLIER_ADVANCES
                default_dir = DirectionChoice.DR
                is_overridden = False
                reclassified_to = f"Supplier Debit reclassified to Supplier Advance Asset ({adv_acc.code} — {adv_acc.name})"

        if is_overridden:
            if not (override_reason or "").strip():
                raise ValidationError(
                    f"Overriding default direction ({default_dir} -> {effective_dir}) on '{account.code} — {account.name}' requires an override reason."
                )
            if user is not None and not _has_perm(company, user, Permissions.OPENING_BALANCE_DIRECTION_OVERRIDE):
                raise ValidationError(
                    f"Permission '{Permissions.OPENING_BALANCE_DIRECTION_OVERRIDE}' is required to override default direction."
                )

        return {
            "account": effective_acc,
            "default_direction": default_dir,
            "direction": effective_dir,
            "opening_category": effective_cat,
            "is_direction_overridden": is_overridden,
            "override_reason": (override_reason or "").strip(),
            "reclassified_note": reclassified_to,
        }


# ---------------------------------------------------------------------------
# 2. Adjustment Account Mapping & Profile Studio Service
# ---------------------------------------------------------------------------


class OpeningBalanceMappingService:
    """Manages category-specific Opening Balance Adjustment Equity accounts (390001..390012)."""

    ADJUSTMENT_ACCOUNTS: list[tuple[str, str]] = [
        ("390001", "Opening Balance Adjustment — Control Clearing"),
        ("390002", "Opening Balance Adjustment — Bank & Cash"),
        ("390003", "Opening Balance Adjustment — Accounts Receivable"),
        ("390004", "Opening Balance Adjustment — Accounts Payable"),
        ("390005", "Opening Balance Adjustment — Advances"),
        ("390006", "Opening Balance Adjustment — Fixed Assets"),
        ("390007", "Opening Balance Adjustment — Inventory"),
        ("390008", "Opening Balance Adjustment — Loans & Credit Facilities"),
        ("390009", "Opening Balance Adjustment — Tax & Statutory"),
        ("390010", "Opening Balance Migration Equity"),
        ("390011", "Opening Balance Equity Clearing"),
        ("390012", "Prior Period Retained Earnings Opening"),
    ]

    CATEGORY_ACCOUNT_CODE: dict[str, tuple[str, str, str]] = {
        OpeningCategory.BANK: ("390002", DirectionChoice.CR, "Counterpart equity clearing for opening Bank accounts"),
        OpeningCategory.CASH: ("390002", DirectionChoice.CR, "Counterpart equity clearing for opening Cash & Imprest vaults"),
        OpeningCategory.DEBTORS: ("390003", DirectionChoice.CR, "Counterpart equity clearing for Customer Receivable openings"),
        OpeningCategory.RETENTION_RECEIVABLE: ("390003", DirectionChoice.CR, "Counterpart equity clearing for Retention Receivable openings"),
        OpeningCategory.CREDITORS: ("390004", DirectionChoice.DR, "Counterpart equity clearing for Supplier / Subcontractor Payable openings"),
        OpeningCategory.RETENTION_PAYABLE: ("390004", DirectionChoice.DR, "Counterpart equity clearing for Retention Payable openings"),
        OpeningCategory.EMPLOYEE_ADVANCES: ("390005", DirectionChoice.CR, "Counterpart equity clearing for Employee Advances"),
        OpeningCategory.SUPPLIER_ADVANCES: ("390005", DirectionChoice.CR, "Counterpart equity clearing for Supplier Advances"),
        OpeningCategory.CUSTOMER_ADVANCES: ("390005", DirectionChoice.DR, "Counterpart equity clearing for Customer Advances"),
        OpeningCategory.FIXED_ASSETS: ("390006", DirectionChoice.CR, "Counterpart equity clearing for Fixed Assets & Machinery"),
        OpeningCategory.ACCUM_DEPRECIATION: ("390006", DirectionChoice.DR, "Counterpart equity clearing for Accumulated Depreciation"),
        OpeningCategory.INVENTORY: ("390007", DirectionChoice.CR, "Counterpart equity clearing for Inventory & Stores stock"),
        OpeningCategory.LOANS: ("390008", DirectionChoice.DR, "Counterpart equity clearing for Term & Project Loans"),
        OpeningCategory.OD_CC: ("390008", DirectionChoice.DR, "Counterpart equity clearing for OD / CC Credit Facilities"),
        OpeningCategory.TAX_RECEIVABLE: ("390009", DirectionChoice.CR, "Counterpart equity clearing for Tax / VAT / TDS Receivable"),
        OpeningCategory.TAX_PAYABLE: ("390009", DirectionChoice.DR, "Counterpart equity clearing for Tax / VAT / TDS Payable"),
        OpeningCategory.EQUITY: ("390010", DirectionChoice.DR, "Counterpart equity clearing for Capital & Retained Earnings"),
        OpeningCategory.OTHER: ("390001", DirectionChoice.CR, "General Opening Balance Control Clearing"),
    }

    @staticmethod
    def find_or_create_control_account(company, role: str) -> Account:
        acc = Account.objects.filter(company=company, control_role=role, is_group=False, is_active=True).first()
        if acc:
            return acc
        defaults_map = {
            Account.ControlRole.CUSTOMER_ADVANCE: ("2070", "Customer / Mobilization Advances", Account.AccountType.LIABILITY),
            Account.ControlRole.SUPPLIER_ADVANCE: ("1180", "Supplier Advances", Account.AccountType.ASSET),
            Account.ControlRole.SUNDRY_DEBTORS: ("1100", "Sundry Debtors", Account.AccountType.ASSET),
            Account.ControlRole.SUNDRY_CREDITORS: ("2010", "Sundry Creditors", Account.AccountType.LIABILITY),
            Account.ControlRole.BANK: ("1020", "Bank Accounts", Account.AccountType.ASSET),
            Account.ControlRole.CASH: ("1010", "Cash in Hand", Account.AccountType.ASSET),
            Account.ControlRole.RETENTION_RECEIVABLE: ("1160", "Retention Receivable", Account.AccountType.ASSET),
            Account.ControlRole.RETENTION_PAYABLE: ("2060", "Retention Payable", Account.AccountType.LIABILITY),
        }
        code, name, atype = defaults_map.get(role, ("1990", f"{role.replace('_', ' ').title()}", Account.AccountType.ASSET))
        existing = Account.objects.filter(company=company, code=code).first()
        if existing:
            return existing
        return Account.objects.create(
            company=company,
            code=code,
            name=name,
            account_type=atype,
            control_role=role,
            allow_direct_posting=True,
            is_control_account=True,
        )

    @classmethod
    @transaction.atomic
    def ensure_default_adjustment_accounts(cls, *, company, fiscal_year: FiscalYear | None = None) -> list[OpeningBalanceAdjustmentMapping]:
        fy = fiscal_year or _active_fiscal_year(company)
        group_acc, _ = Account.objects.get_or_create(
            company=company,
            code="3900",
            defaults={
                "name": "Opening Balance Adjustment Equity",
                "account_type": Account.AccountType.EQUITY,
                "account_class": Account.AccountClass.EQUITY,
                "is_group": True,
                "allow_direct_posting": False,
                "nfrs_mapping": "NAS 01 / Equity Clearing",
            },
        )
        acc_by_code: dict[str, Account] = {}
        for code, name in cls.ADJUSTMENT_ACCOUNTS:
            acc, _ = Account.objects.get_or_create(
                company=company,
                code=code,
                defaults={
                    "parent": group_acc,
                    "name": name,
                    "account_type": Account.AccountType.EQUITY,
                    "account_class": Account.AccountClass.EQUITY,
                    "is_group": False,
                    "allow_direct_posting": True,
                    "is_control_account": False,
                    "nfrs_mapping": "NAS 01 / Opening Clearing",
                },
            )
            acc_by_code[code] = acc

        bs_cutoff = ""
        try:
            bs_cutoff = ad_to_bs(fy.start_date).isoformat()
        except Exception:
            bs_cutoff = ""
        OpeningBalanceProfile.objects.get_or_create(
            company=company,
            fiscal_year=fy,
            defaults={
                "conversion_cutoff_date": fy.start_date,
                "bs_cutoff_date": bs_cutoff,
                "default_clearing_account": acc_by_code["390001"],
                "default_equity_account": acc_by_code["390010"],
            },
        )

        mappings: list[OpeningBalanceAdjustmentMapping] = []
        for cat, (code, nbal, desc) in cls.CATEGORY_ACCOUNT_CODE.items():
            mapping, _ = OpeningBalanceAdjustmentMapping.objects.get_or_create(
                company=company,
                category=cat,
                defaults={
                    "fiscal_year": fy,
                    "adjustment_account": acc_by_code[code],
                    "normal_balance": nbal,
                    "description": desc,
                    "is_active": True,
                },
            )
            mappings.append(mapping)
        return mappings

    @classmethod
    def get_adjustment_account(cls, *, company, category: str) -> Account:
        cls.ensure_default_adjustment_accounts(company=company)
        mapping = OpeningBalanceAdjustmentMapping.objects.select_related("adjustment_account").filter(
            company=company, category=category, is_active=True
        ).first()
        if mapping and mapping.adjustment_account:
            return mapping.adjustment_account
        return Account.objects.get(company=company, code="390001")

    @classmethod
    @transaction.atomic
    def set_mapping(
        cls,
        *,
        company,
        category: str,
        adjustment_account: Account,
        normal_balance: str = DirectionChoice.CR,
        require_approval: bool = False,
        description: str = "",
        user=None,
    ) -> OpeningBalanceAdjustmentMapping:
        if adjustment_account.company_id != company.id:
            raise ValidationError("Adjustment account belongs to another company.")
        if adjustment_account.is_group:
            raise ValidationError("Opening Balance Adjustment Account cannot be a Group account.")
        if adjustment_account.account_type in (Account.AccountType.INCOME, Account.AccountType.EXPENSE):
            raise ValidationError(
                f"Account '{adjustment_account.code} — {adjustment_account.name}' is an {adjustment_account.account_type} account. Opening balances must never balance against current-year Income or Expense accounts."
            )
        cls.ensure_default_adjustment_accounts(company=company)
        mapping, _ = OpeningBalanceAdjustmentMapping.objects.update_or_create(
            company=company,
            category=category,
            defaults={
                "adjustment_account": adjustment_account,
                "normal_balance": normal_balance,
                "require_approval": require_approval,
                "description": description or f"Configured for {category}",
                "is_active": True,
            },
        )
        _audit_ob(
            company=company,
            action="OB_MAPPING_UPDATED",
            entity_type="OpeningBalanceAdjustmentMapping",
            entity_id=str(mapping.id),
            actor=user,
            new_state={"category": category, "adjustment_account": adjustment_account.code},
        )
        return mapping


# ---------------------------------------------------------------------------
# 3. Validation, AD/BS Dates & Cut-off Guard Service
# ---------------------------------------------------------------------------


class OpeningBalanceValidationService:
    """Validates AD/BS dates, fiscal periods, zero-value guards, duplicates, and mid-year migration overrides."""

    @staticmethod
    def resolve_opening_dates(*, company, opening_date: date | None = None, bs_date_str: str | None = None) -> tuple[date, str]:
        if bs_date_str and not opening_date:
            parts = [int(p) for p in str(bs_date_str).strip().split("-")]
            if len(parts) != 3:
                raise ValidationError(f"Invalid BS date format '{bs_date_str}'; expected YYYY-MM-DD.")
            opening_date = bs_to_ad(parts[0], parts[1], parts[2])
        if not opening_date:
            fy = _active_fiscal_year(company)
            opening_date = fy.start_date
        if not bs_date_str:
            try:
                bs_date_str = ad_to_bs(opening_date).isoformat()
            except Exception:
                bs_date_str = ""
        return opening_date, bs_date_str

    @staticmethod
    def get_or_create_profile(*, company, opening_date: date | None = None) -> OpeningBalanceProfile:
        fy = _active_fiscal_year(company, as_of=opening_date)
        OpeningBalanceMappingService.ensure_default_adjustment_accounts(company=company, fiscal_year=fy)
        return OpeningBalanceProfile.objects.get(company=company, fiscal_year=fy)

    @staticmethod
    def check_migration_cutoff_guard(
        *,
        company,
        user=None,
        opening_date: date,
        migration_override_reason: str = "",
        is_carry_forward: bool = False,
    ) -> OpeningBalanceProfile:
        profile = OpeningBalanceValidationService.get_or_create_profile(company=company, opening_date=opening_date)
        if profile.is_migration_locked and not is_carry_forward:
            raise ValidationError("Opening balance migration is locked for this financial year. Unlock in Configuration Studio to make corrections.")

        period = FiscalPeriod.objects.select_related("fiscal_year").filter(
            fiscal_year__company=company, start_date__lte=opening_date, end_date__gte=opening_date
        ).first()
        if not period:
            raise ValidationError(f"No fiscal period covers opening date {opening_date}.")
        if period.fiscal_year.is_closed or period.status != FiscalPeriod.Status.OPEN:
            raise ValidationError(f"Fiscal period '{period.name}' is {period.status}; opening balance posting blocked.")

        if (
            not is_carry_forward
            and opening_date > profile.conversion_cutoff_date
            and not profile.allow_live_midyear_migration
        ):
            reason_clean = (migration_override_reason or "").strip()
            if not reason_clean:
                raise ValidationError(
                    f"Opening date {opening_date} is after the conversion cut-off date ({profile.conversion_cutoff_date}). "
                    "For live mid-year accounts, record a Receipt/Contra/Payment voucher instead, or supply an authorized migration_override_reason."
                )
            if user is not None and not _has_perm(company, user, Permissions.OPENING_BALANCE_MIGRATION_OVERRIDE):
                raise ValidationError(
                    f"Permission '{Permissions.OPENING_BALANCE_MIGRATION_OVERRIDE}' is required to enter opening balances past conversion cutoff ({profile.conversion_cutoff_date})."
                )
        return profile

    @staticmethod
    def validate_single_amount(amount: Decimal) -> Decimal:
        amt = _q2(amount)
        if amt <= Decimal("0.00"):
            raise ValidationError("Opening balance amount must be greater than zero when creating an opening entry.")
        return amt


# ---------------------------------------------------------------------------
# 4. Opening Balance Creation, Preview & Voucher Lifecycle Service
# ---------------------------------------------------------------------------


class OpeningBalanceCreationService:
    """High-level entry points for inline entity creation + Opening Balance Studio."""

    @classmethod
    def preview_opening_accounting(
        cls,
        *,
        company,
        account: Account,
        amount: Decimal,
        direction: str = "",
        adjustment_account: Account | None = None,
        party: Party | None = None,
        category: str = "",
        opening_date: date | None = None,
        bs_date: str = "",
        currency: str = "NPR",
        exchange_rate: Decimal = Decimal("1.000000"),
        override_reason: str = "",
        user=None,
    ) -> dict[str, Any]:
        op_date, bs_str = OpeningBalanceValidationService.resolve_opening_dates(
            company=company, opening_date=opening_date, bs_date_str=bs_date
        )
        amt = _q2(amount)
        rate = _q6(exchange_rate)
        resolved = OpeningBalanceDirectionService.resolve_account_and_direction(
            company=company,
            user=user,
            account=account,
            party=party,
            requested_direction=direction,
            category=category,
            override_reason=override_reason or ("Preview override" if direction else ""),
        )
        target_acc = resolved["account"]
        eff_dir = resolved["direction"]
        adj_acc = adjustment_account or OpeningBalanceMappingService.get_adjustment_account(
            company=company, category=resolved["opening_category"]
        )
        if adj_acc.account_type in (Account.AccountType.INCOME, Account.AccountType.EXPENSE):
            raise ValidationError("Adjustment account cannot be an Income or Expense account.")

        base_amt = (amt * rate).quantize(Q2, rounding=ROUND_HALF_UP)
        dr_1 = base_amt if eff_dir == DirectionChoice.DR else Decimal("0.00")
        cr_1 = base_amt if eff_dir == DirectionChoice.CR else Decimal("0.00")
        lines = [
            {
                "account_code": target_acc.code,
                "account_name": target_acc.name,
                "party_name": party.name if party else "",
                "debit": str(dr_1),
                "credit": str(cr_1),
                "role": "TARGET_LEDGER",
            },
            {
                "account_code": adj_acc.code,
                "account_name": adj_acc.name,
                "party_name": "",
                "debit": str(cr_1),
                "credit": str(dr_1),
                "role": "ADJUSTMENT_CLEARING",
            },
        ]
        return {
            "opening_date": op_date.isoformat(),
            "bs_date": bs_str,
            "currency": currency,
            "exchange_rate": str(rate),
            "default_direction": resolved["default_direction"],
            "effective_direction": eff_dir,
            "opening_category": resolved["opening_category"],
            "is_direction_overridden": resolved["is_direction_overridden"],
            "reclassified_note": resolved["reclassified_note"],
            "adjustment_account": {"id": str(adj_acc.id), "code": adj_acc.code, "name": adj_acc.name},
            "base_amount": str(base_amt),
            "journal_lines": lines,
            "is_balanced": base_amt > 0,
        }

    @classmethod
    @transaction.atomic
    def create_single_account_opening(
        cls,
        *,
        company,
        user,
        account: Account,
        amount: Decimal,
        opening_date: date | None = None,
        bs_date: str = "",
        direction: str = "",
        adjustment_account: Account | None = None,
        party: Party | None = None,
        project=None,
        category: str = "",
        currency: str = "NPR",
        exchange_rate: Decimal = Decimal("1.000000"),
        source_entity_type: str = "Account",
        source_entity_id: str = "",
        reference_no: str = "",
        narration: str = "",
        override_reason: str = "",
        migration_override_reason: str = "",
        idempotency_key: str = "",
        auto_post: bool = True,
        entry_mode: str = OpeningBalanceVoucher.EntryMode.INDIVIDUAL,
    ) -> OpeningBalanceVoucher | None:
        amt = _q2(amount)
        if amt <= Decimal("0.00"):
            return None

        if idempotency_key:
            existing = OpeningBalanceVoucher.objects.filter(company=company, idempotency_key=idempotency_key).first()
            if existing:
                return existing

        op_date, bs_str = OpeningBalanceValidationService.resolve_opening_dates(
            company=company, opening_date=opening_date, bs_date_str=bs_date
        )
        profile = OpeningBalanceValidationService.check_migration_cutoff_guard(
            company=company,
            user=user,
            opening_date=op_date,
            migration_override_reason=migration_override_reason,
        )
        resolved = OpeningBalanceDirectionService.resolve_account_and_direction(
            company=company,
            user=user,
            account=account,
            party=party,
            requested_direction=direction,
            category=category,
            override_reason=override_reason,
        )
        target_acc = resolved["account"]
        adj_acc = adjustment_account or OpeningBalanceMappingService.get_adjustment_account(
            company=company, category=resolved["opening_category"]
        )
        if adj_acc.account_type in (Account.AccountType.INCOME, Account.AccountType.EXPENSE):
            raise ValidationError("Opening balance adjustment account cannot be an Income or Expense account.")
        if target_acc.is_group:
            raise ValidationError(f"Cannot record opening balance on group account {target_acc.code}.")

        rate = _q6(exchange_rate)
        base_amt = (amt * rate).quantize(Q2, rounding=ROUND_HALF_UP)
        eff_dir = resolved["direction"]
        dr = amt if eff_dir == DirectionChoice.DR else Decimal("0.00")
        cr = amt if eff_dir == DirectionChoice.CR else Decimal("0.00")
        bdr = base_amt if eff_dir == DirectionChoice.DR else Decimal("0.00")
        bcr = base_amt if eff_dir == DirectionChoice.CR else Decimal("0.00")

        fy = _active_fiscal_year(company, as_of=op_date)
        ob = OpeningBalanceVoucher.objects.create(
            company=company,
            fiscal_year=fy,
            ob_number=_next_ob_number(company),
            entry_mode=entry_mode,
            opening_date=op_date,
            bs_date=bs_str,
            currency=currency or company.base_currency,
            exchange_rate=rate,
            source_entity_type=source_entity_type,
            source_entity_id=str(source_entity_id or target_acc.id),
            is_historical_migration=op_date <= profile.conversion_cutoff_date,
            migration_override_reason=migration_override_reason,
            status=OpeningBalanceVoucher.Status.DRAFT,
            total_debit=base_amt,
            total_credit=base_amt,
            supporting_doc_ref=reference_no,
            narration=narration or f"Opening balance for {target_acc.code} — {target_acc.name}",
            idempotency_key=idempotency_key,
            prepared_by=user,
        )
        OpeningBalanceLine.objects.create(
            ob_voucher=ob,
            line_no=1,
            account=target_acc,
            party=party,
            project=project,
            opening_category=resolved["opening_category"],
            direction=eff_dir,
            default_direction=resolved["default_direction"],
            is_direction_overridden=resolved["is_direction_overridden"],
            override_reason=resolved["override_reason"],
            amount=amt,
            debit=dr,
            credit=cr,
            currency=currency or company.base_currency,
            exchange_rate=rate,
            base_debit=bdr,
            base_credit=bcr,
            adjustment_account=adj_acc,
            reference_no=reference_no,
            narration=narration or f"Opening {target_acc.name}",
        )
        _audit_ob(
            company=company,
            action="OB_CREATED",
            entity_type="OpeningBalanceVoucher",
            entity_id=str(ob.id),
            actor=user,
            new_state={"ob_number": ob.ob_number, "account": target_acc.code, "direction": eff_dir, "amount": str(amt)},
        )

        if auto_post:
            ob = OpeningBalanceVoucherService.submit_approve_and_post(ob=ob, user=user)
        return ob

    @classmethod
    @transaction.atomic
    def create_party_billwise_opening(
        cls,
        *,
        company,
        user,
        party: Party,
        opening_date: date | None = None,
        bs_date: str = "",
        currency: str = "NPR",
        exchange_rate: Decimal = Decimal("1.000000"),
        lump_sum_amount: Decimal | None = None,
        direction: str = "",
        bill_items: list[dict] | None = None,
        reference_no: str = "",
        narration: str = "",
        override_reason: str = "",
        migration_override_reason: str = "",
        idempotency_key: str = "",
        auto_post: bool = True,
    ) -> OpeningBalanceVoucher | None:
        items = bill_items or []
        if not items and (lump_sum_amount is None or _q2(lump_sum_amount) <= 0):
            return None

        if idempotency_key:
            existing = OpeningBalanceVoucher.objects.filter(company=company, idempotency_key=idempotency_key).first()
            if existing:
                return existing

        op_date, bs_str = OpeningBalanceValidationService.resolve_opening_dates(
            company=company, opening_date=opening_date, bs_date_str=bs_date
        )
        profile = OpeningBalanceValidationService.check_migration_cutoff_guard(
            company=company,
            user=user,
            opening_date=op_date,
            migration_override_reason=migration_override_reason,
        )
        fy = _active_fiscal_year(company, as_of=op_date)
        default_ctrl = party.control_account or OpeningBalanceMappingService.find_or_create_control_account(
            company,
            Account.ControlRole.SUNDRY_DEBTORS if party.party_type == Party.PartyType.CUSTOMER else Account.ControlRole.SUNDRY_CREDITORS,
        )

        if not items:
            amt = _q2(lump_sum_amount)
            ref = reference_no or f"OP-{party.code}"
            items = [
                {
                    "invoice_ref": ref,
                    "invoice_date": op_date,
                    "due_date": op_date + timedelta(days=int(party.payment_terms_days or 30)),
                    "outstanding_amount": amt,
                    "original_amount": amt,
                    "direction": direction,
                    "project": party.project,
                }
            ]

        total_items_amt = sum((_q2(i.get("outstanding_amount") or i.get("amount")) for i in items), Decimal("0.00"))
        if lump_sum_amount is not None and _q2(lump_sum_amount) > 0 and _q2(lump_sum_amount) != total_items_amt:
            raise ValidationError(
                f"Party opening total ({_q2(lump_sum_amount)}) must equal sum of bill-wise outstanding items ({total_items_amt})."
            )
        if total_items_amt <= Decimal("0.00"):
            raise ValidationError("Bill-wise opening total must exceed zero.")

        seen_refs: set[str] = set()
        rate = _q6(exchange_rate)
        ob = OpeningBalanceVoucher.objects.create(
            company=company,
            fiscal_year=fy,
            ob_number=_next_ob_number(company),
            entry_mode=OpeningBalanceVoucher.EntryMode.PARTY,
            opening_date=op_date,
            bs_date=bs_str,
            currency=currency or company.base_currency,
            exchange_rate=rate,
            source_entity_type="Party",
            source_entity_id=str(party.id),
            is_historical_migration=op_date <= profile.conversion_cutoff_date,
            migration_override_reason=migration_override_reason,
            status=OpeningBalanceVoucher.Status.DRAFT,
            supporting_doc_ref=reference_no,
            narration=narration or f"Bill-wise opening balance for {party.code} — {party.name}",
            idempotency_key=idempotency_key,
            prepared_by=user,
        )

        total_base = Decimal("0.00")
        for idx, item in enumerate(items, start=1):
            inv_ref = str(item.get("invoice_ref") or f"OP-{party.code}-{idx:02d}").strip()
            if inv_ref in seen_refs:
                raise ValidationError(f"Duplicate bill reference '{inv_ref}' in same opening balance submission.")
            seen_refs.add(inv_ref)
            if OpeningBalancePartyReference.objects.filter(
                company=company, fiscal_year=fy, party=party, reference_no=inv_ref
            ).exists():
                raise ValidationError(f"Opening reference '{inv_ref}' already exists for {party.name} in FY {fy.name}.")

            out_amt = _q2(item.get("outstanding_amount") or item.get("amount"))
            orig_amt = _q2(item.get("original_amount") or out_amt)
            settled_amt = _q2(item.get("settled_before_cutoff") or max(Decimal("0.00"), orig_amt - out_amt))
            if out_amt <= Decimal("0.00"):
                raise ValidationError(f"Bill '{inv_ref}' outstanding amount must exceed zero.")

            raw_inv_dt = item.get("invoice_date") or op_date
            inv_dt = date.fromisoformat(raw_inv_dt) if isinstance(raw_inv_dt, str) else raw_inv_dt
            raw_due_dt = item.get("due_date") or (inv_dt + timedelta(days=int(party.payment_terms_days or 30)))
            due_dt = date.fromisoformat(raw_due_dt) if isinstance(raw_due_dt, str) else raw_due_dt
            if inv_dt > op_date:
                raise ValidationError(f"Bill '{inv_ref}' invoice_date ({inv_dt}) cannot be later than opening_date ({op_date}).")

            req_dir = item.get("direction") or direction
            resolved = OpeningBalanceDirectionService.resolve_account_and_direction(
                company=company,
                user=user,
                account=default_ctrl,
                party=party,
                requested_direction=req_dir,
                override_reason=override_reason,
            )
            target_acc = resolved["account"]
            adj_acc = OpeningBalanceMappingService.get_adjustment_account(
                company=company, category=resolved["opening_category"]
            )
            eff_dir = resolved["direction"]
            base_amt = (out_amt * rate).quantize(Q2, rounding=ROUND_HALF_UP)
            total_base += base_amt

            ob_line = OpeningBalanceLine.objects.create(
                ob_voucher=ob,
                line_no=idx,
                account=target_acc,
                party=party,
                project=item.get("project") or party.project,
                opening_category=resolved["opening_category"],
                direction=eff_dir,
                default_direction=resolved["default_direction"],
                is_direction_overridden=resolved["is_direction_overridden"],
                override_reason=resolved["override_reason"],
                amount=out_amt,
                debit=out_amt if eff_dir == DirectionChoice.DR else Decimal("0.00"),
                credit=out_amt if eff_dir == DirectionChoice.CR else Decimal("0.00"),
                currency=currency or company.base_currency,
                exchange_rate=rate,
                base_debit=base_amt if eff_dir == DirectionChoice.DR else Decimal("0.00"),
                base_credit=base_amt if eff_dir == DirectionChoice.CR else Decimal("0.00"),
                adjustment_account=adj_acc,
                reference_no=inv_ref,
                invoice_date=inv_dt,
                due_date=due_dt,
                narration=item.get("narration") or f"Opening Bill {inv_ref} — {party.name}",
            )
            OpeningBalanceSubledgerItem.objects.create(
                company=company,
                ob_line=ob_line,
                party=party,
                project=item.get("project") or party.project,
                doc_kind=item.get("doc_kind") or (
                    "CUSTOMER_ADVANCE" if resolved["opening_category"] == OpeningCategory.CUSTOMER_ADVANCES
                    else "SUPPLIER_ADVANCE" if resolved["opening_category"] == OpeningCategory.SUPPLIER_ADVANCES
                    else "SALES_INVOICE" if party.party_type == Party.PartyType.CUSTOMER
                    else "PURCHASE_INVOICE"
                ),
                invoice_ref=inv_ref,
                invoice_date=inv_dt,
                due_date=due_dt,
                original_amount=orig_amt,
                settled_before_cutoff=settled_amt,
                outstanding_amount=out_amt,
                currency=currency or company.base_currency,
                exchange_rate=rate,
                contract_ref=item.get("contract_ref", ""),
            )

        ob.total_debit = total_base
        ob.total_credit = total_base
        ob.save(update_fields=["total_debit", "total_credit"])

        if auto_post:
            ob = OpeningBalanceVoucherService.submit_approve_and_post(ob=ob, user=user)
        return ob


class OpeningBalanceVoucherService:
    """Workflow state transitions (Submit, Approve, Reject, Post) for OpeningBalanceVoucher."""

    @staticmethod
    @transaction.atomic
    def submit(*, ob: OpeningBalanceVoucher, user, comment: str = "") -> OpeningBalanceVoucher:
        if ob.status not in (OpeningBalanceVoucher.Status.DRAFT, OpeningBalanceVoucher.Status.REJECTED):
            raise ValidationError(f"Cannot submit opening voucher in status '{ob.status}'.")
        ob.status = OpeningBalanceVoucher.Status.SUBMITTED
        ob.save(update_fields=["status", "updated_at"])
        OpeningBalanceApproval.objects.create(
            company=ob.company, ob_voucher=ob, decision="SUBMITTED", actor=user, comment=comment
        )
        return ob

    @staticmethod
    @transaction.atomic
    def approve(*, ob: OpeningBalanceVoucher, user, comment: str = "") -> OpeningBalanceVoucher:
        if not _has_perm(ob.company, user, Permissions.OPENING_BALANCE_APPROVE):
            raise ValidationError(f"Permission '{Permissions.OPENING_BALANCE_APPROVE}' is required to approve opening balances.")
        if ob.status == OpeningBalanceVoucher.Status.DRAFT:
            ob.status = OpeningBalanceVoucher.Status.SUBMITTED
        if ob.status != OpeningBalanceVoucher.Status.SUBMITTED:
            raise ValidationError(f"Cannot approve opening voucher in status '{ob.status}'.")
        ob.status = OpeningBalanceVoucher.Status.APPROVED
        ob.approved_by = user
        ob.approved_at = timezone.now()
        ob.save(update_fields=["status", "approved_by", "approved_at", "updated_at"])
        OpeningBalanceApproval.objects.create(
            company=ob.company, ob_voucher=ob, decision="APPROVED", actor=user, comment=comment
        )
        return ob

    @staticmethod
    @transaction.atomic
    def reject(*, ob: OpeningBalanceVoucher, user, comment: str = "") -> OpeningBalanceVoucher:
        if not _has_perm(ob.company, user, Permissions.OPENING_BALANCE_APPROVE):
            raise ValidationError(f"Permission '{Permissions.OPENING_BALANCE_APPROVE}' is required.")
        if ob.status not in (OpeningBalanceVoucher.Status.SUBMITTED, OpeningBalanceVoucher.Status.APPROVED):
            raise ValidationError(f"Cannot reject opening voucher in status '{ob.status}'.")
        ob.status = OpeningBalanceVoucher.Status.REJECTED
        ob.save(update_fields=["status", "updated_at"])
        OpeningBalanceApproval.objects.create(
            company=ob.company, ob_voucher=ob, decision="REJECTED", actor=user, comment=comment
        )
        return ob

    @classmethod
    @transaction.atomic
    def submit_approve_and_post(cls, *, ob: OpeningBalanceVoucher, user) -> OpeningBalanceVoucher:
        profile = OpeningBalanceValidationService.get_or_create_profile(company=ob.company, opening_date=ob.opening_date)
        if ob.status == OpeningBalanceVoucher.Status.DRAFT:
            cls.submit(ob=ob, user=user, comment="Auto-submitted")
        can_approve = _has_perm(ob.company, user, Permissions.OPENING_BALANCE_APPROVE) or not profile.require_approval
        can_post = _has_perm(ob.company, user, Permissions.OPENING_BALANCE_POST) or not profile.require_approval
        if can_approve and ob.status == OpeningBalanceVoucher.Status.SUBMITTED:
            ob.status = OpeningBalanceVoucher.Status.APPROVED
            ob.approved_by = user
            ob.approved_at = timezone.now()
            ob.save(update_fields=["status", "approved_by", "approved_at", "updated_at"])
            OpeningBalanceApproval.objects.create(
                company=ob.company, ob_voucher=ob, decision="APPROVED", actor=user, comment="Auto-approved"
            )
            if can_post:
                return OpeningBalancePostingService.post_ob_voucher(ob=ob, user=user, bypass_perm_check=True)
        return ob


# ---------------------------------------------------------------------------
# 5. Central GL + Multi-Bill OpenItem Posting Engine Integration
# ---------------------------------------------------------------------------


class OpeningBalancePostingService:
    """Posts an OpeningBalanceVoucher through standard VoucherService + PostingService atomically."""

    @staticmethod
    @transaction.atomic
    def post_ob_voucher(*, ob: OpeningBalanceVoucher, user, bypass_perm_check: bool = False) -> OpeningBalanceVoucher:
        ob = OpeningBalanceVoucher.objects.select_for_update().get(id=ob.id)
        if ob.status == OpeningBalanceVoucher.Status.POSTED and ob.voucher_id:
            return ob
        if not bypass_perm_check and not _has_perm(ob.company, user, Permissions.OPENING_BALANCE_POST):
            raise ValidationError(f"Permission '{Permissions.OPENING_BALANCE_POST}' is required to post opening balances.")
        if ob.status not in (OpeningBalanceVoucher.Status.APPROVED, OpeningBalanceVoucher.Status.DRAFT, OpeningBalanceVoucher.Status.SUBMITTED):
            raise ValidationError(f"Opening voucher '{ob.ob_number}' cannot be posted from status '{ob.status}'.")

        lines = list(ob.lines.select_related("account", "party", "project", "adjustment_account").all())
        if not lines:
            raise ValidationError("Opening balance voucher has no lines.")

        gl_lines: list[dict[str, Any]] = []
        adj_net_by_acc: dict[str, dict[str, Any]] = {}

        for ob_line in lines:
            gl_lines.append(
                {
                    "account": ob_line.account,
                    "party": ob_line.party,
                    "project": ob_line.project,
                    "debit": ob_line.debit,
                    "credit": ob_line.credit,
                    "bill_ref": ob_line.reference_no or ob.supporting_doc_ref or ob.ob_number,
                    "due_date": ob_line.due_date,
                    "description": ob_line.narration or ob.narration or f"Opening Balance ({ob.ob_number})",
                }
            )
            # Counterpart adjustment entry balances each line in its category adjustment account
            adj = ob_line.adjustment_account
            key = f"{adj.id}:{ob_line.project_id or ''}"
            if key not in adj_net_by_acc:
                adj_net_by_acc[key] = {"account": adj, "project": ob_line.project, "net": Decimal("0.00")}
            # When target is Debit, adjustment gets Credit (net -= amt); when target is Credit, adjustment gets Debit (net += amt)
            adj_net_by_acc[key]["net"] += (ob_line.credit - ob_line.debit)

        for entry in adj_net_by_acc.values():
            net = entry["net"]
            if net == Decimal("0.00"):
                continue
            gl_lines.append(
                {
                    "account": entry["account"],
                    "party": None,
                    "project": entry["project"],
                    "debit": net if net > 0 else Decimal("0.00"),
                    "credit": -net if net < 0 else Decimal("0.00"),
                    "description": f"Opening Balance Adjustment ({ob.ob_number})",
                    "is_auto_generated": True,
                }
            )

        voucher = VoucherService.create_draft(
            company=ob.company,
            user=user,
            data={
                "voucher_type": Voucher.VoucherType.OPENING_BALANCE,
                "voucher_date": ob.opening_date,
                "currency": ob.currency,
                "exchange_rate": ob.exchange_rate,
                "reference_no": ob.ob_number,
                "supplier_invoice_no": ob.supporting_doc_ref,
                "narration": ob.narration or f"Opening Balance Migration — {ob.ob_number}",
                "is_control_override": any(not l.party_id and l.account.requires_subledger for l in lines),
                "override_reason": "Opening balance migration control line" if any(not l.party_id and l.account.requires_subledger for l in lines) else "",
                "operational_payload": {"ob_voucher_id": str(ob.id), "ob_number": ob.ob_number},
                "idempotency_key": f"ob-post-{ob.id}",
            },
            lines_data=gl_lines,
        )
        voucher.status = Voucher.Status.APPROVED
        voucher.approved_by = ob.approved_by or user
        voucher.save(update_fields=["status", "approved_by"])

        PostingService.post_voucher(voucher=voucher, user=user)

        # Link created OpenItems & record PartyReference uniqueness
        for ob_line in lines:
            if ob_line.party_id:
                sub_items = list(ob_line.subledger_items.all())
                if sub_items:
                    for si in sub_items:
                        oi = OpenItem.objects.filter(
                            company=ob.company, voucher=voucher, party=si.party, document_no=si.invoice_ref
                        ).first()
                        if oi:
                            si.open_item = oi
                            si.save(update_fields=["open_item"])
                        OpeningBalancePartyReference.objects.get_or_create(
                            company=ob.company,
                            fiscal_year=ob.fiscal_year,
                            party=si.party,
                            reference_no=si.invoice_ref,
                            defaults={
                                "classification": (
                                    "CUSTOMER_ADVANCE" if ob_line.opening_category == OpeningCategory.CUSTOMER_ADVANCES
                                    else "SUPPLIER_ADVANCE" if ob_line.opening_category == OpeningCategory.SUPPLIER_ADVANCES
                                    else "DEBTOR" if ob_line.party.party_type == Party.PartyType.CUSTOMER
                                    else "CREDITOR"
                                ),
                                "opening_amount": si.outstanding_amount,
                                "ob_voucher": ob,
                            },
                        )

        now = timezone.now()
        ob.voucher = voucher
        ob.status = OpeningBalanceVoucher.Status.POSTED
        ob.approved_by = ob.approved_by or user
        ob.approved_at = ob.approved_at or now
        ob.posted_by = user
        ob.posted_at = now
        ob.save(update_fields=["voucher", "status", "approved_by", "approved_at", "posted_by", "posted_at", "updated_at"])

        _audit_ob(
            company=ob.company,
            action="OB_POSTED",
            entity_type="OpeningBalanceVoucher",
            entity_id=str(ob.id),
            actor=user,
            new_state={"ob_number": ob.ob_number, "voucher_no": voucher.voucher_no, "total_debit": str(ob.total_debit)},
        )
        return ob


# ---------------------------------------------------------------------------
# 6. Bulk CSV / XLSX Migration Import Service
# ---------------------------------------------------------------------------


class OpeningBalanceImportService:
    """Validates and converts CSV/XLSX bulk opening schedules into OpeningBalanceVouchers."""

    @staticmethod
    @transaction.atomic
    def validate_upload(*, company, user, batch_name: str, rows_data: list[dict] | None = None, file_bytes: bytes | None = None, file_ext: str = "csv", fiscal_year: FiscalYear | None = None) -> OpeningBalanceImport:
        fy = fiscal_year or _active_fiscal_year(company)
        parsed_rows: list[dict[str, Any]] = []
        if rows_data is not None:
            parsed_rows = rows_data
        elif file_bytes is not None:
            if file_ext.lower() in ("xlsx", "xlsm"):
                import openpyxl
                wb = openpyxl.load_workbook(io.BytesIO(file_bytes), data_only=True)
                ws = wb.active
                headers = [str(c.value or "").strip().lower() for c in next(ws.iter_rows(min_row=1, max_row=1))]
                for r in ws.iter_rows(min_row=2, values_only=True):
                    if not any(r):
                        continue
                    parsed_rows.append({headers[i]: r[i] for i in range(min(len(headers), len(r)))})
            else:
                text = file_bytes.decode("utf-8-sig")
                reader = csv.DictReader(io.StringIO(text))
                parsed_rows = [{(k or "").strip().lower(): v for k, v in row.items()} for row in reader]

        batch = OpeningBalanceImport.objects.create(
            company=company,
            fiscal_year=fy,
            batch_name=batch_name or f"Migration Batch {timezone.localdate().isoformat()}",
            total_rows=len(parsed_rows),
            uploaded_by=user,
        )

        acc_map = {a.code.strip(): a for a in Account.objects.filter(company=company, is_active=True)}
        party_map = {p.code.strip(): p for p in Party.objects.filter(company=company, is_active=True)}
        valid_count = 0
        error_count = 0

        for idx, raw in enumerate(parsed_rows, start=1):
            acode = str(raw.get("account_code") or "").strip()
            pcode = str(raw.get("party_code") or "").strip()
            dr = _q2(raw.get("debit") or 0)
            cr = _q2(raw.get("credit") or 0)
            ref = str(raw.get("reference_no") or "").strip()
            ccy = str(raw.get("currency") or company.base_currency).strip().upper()[:3]

            err_msgs = []
            acc = acc_map.get(acode)
            if not acc:
                err_msgs.append(f"Unknown account_code '{acode}'")
            elif acc.is_group:
                err_msgs.append(f"Account '{acode}' is a group account")

            if pcode and pcode not in party_map:
                err_msgs.append(f"Unknown party_code '{pcode}'")
            if acc and acc.requires_subledger and not pcode:
                err_msgs.append(f"Control account '{acode}' requires a party_code")

            if (dr > 0 and cr > 0) or (dr == 0 and cr == 0):
                err_msgs.append("Must provide strictly Debit > 0 OR Credit > 0")

            op_dt = None
            raw_dt = raw.get("opening_date") or raw.get("bs_date")
            try:
                if raw_dt:
                    if isinstance(raw_dt, date):
                        op_dt = raw_dt
                    elif raw.get("bs_date") and not raw.get("opening_date"):
                        op_dt, _ = OpeningBalanceValidationService.resolve_opening_dates(company=company, bs_date_str=str(raw_dt))
                    else:
                        op_dt = date.fromisoformat(str(raw_dt).strip()[:10])
                else:
                    op_dt = fy.start_date
            except Exception as exc:
                err_msgs.append(f"Invalid date '{raw_dt}': {exc}")

            due_dt = None
            if raw.get("due_date"):
                try:
                    raw_due = raw["due_date"]
                    due_dt = raw_due if isinstance(raw_due, date) else date.fromisoformat(str(raw_due).strip()[:10])
                except Exception:
                    err_msgs.append(f"Invalid due_date '{raw['due_date']}'")

            is_valid = len(err_msgs) == 0
            if is_valid:
                valid_count += 1
            else:
                error_count += 1

            OpeningBalanceImportLine.objects.create(
                batch=batch,
                row_no=idx,
                account_code=acode[:32],
                party_code=pcode[:32],
                opening_date=op_dt,
                debit=dr,
                credit=cr,
                currency=ccy or company.base_currency,
                reference_no=ref[:64],
                due_date=due_dt,
                is_valid=is_valid,
                error_message="; ".join(err_msgs)[:255],
            )

        batch.valid_rows = valid_count
        batch.error_rows = error_count
        batch.status = "VALIDATED" if error_count == 0 and valid_count > 0 else "HAS_ERRORS"
        batch.save(update_fields=["valid_rows", "error_rows", "status"])
        return batch

    @staticmethod
    @transaction.atomic
    def convert_batch_to_voucher(*, batch: OpeningBalanceImport, user, auto_post: bool = False, migration_override_reason: str = "") -> OpeningBalanceVoucher:
        if batch.error_rows > 0:
            raise ValidationError(f"Batch '{batch.batch_name}' contains {batch.error_rows} invalid rows; fix errors before converting.")
        if batch.ob_voucher_id:
            return batch.ob_voucher
        rows = list(batch.rows.filter(is_valid=True))
        if not rows:
            raise ValidationError("No valid rows in import batch.")

        op_date = rows[0].opening_date or batch.fiscal_year.start_date
        OpeningBalanceValidationService.check_migration_cutoff_guard(
            company=batch.company, user=user, opening_date=op_date, migration_override_reason=migration_override_reason
        )
        _, bs_str = OpeningBalanceValidationService.resolve_opening_dates(company=batch.company, opening_date=op_date)
        acc_map = {a.code: a for a in Account.objects.filter(company=batch.company, is_active=True)}
        party_map = {p.code: p for p in Party.objects.filter(company=batch.company, is_active=True)}

        total_dr = sum((r.debit for r in rows), Decimal("0.00"))
        total_cr = sum((r.credit for r in rows), Decimal("0.00"))
        net_diff = total_dr - total_cr  # Net side handled in 390001/category adjustment per line cleanly

        ob = OpeningBalanceVoucher.objects.create(
            company=batch.company,
            fiscal_year=batch.fiscal_year,
            ob_number=_next_ob_number(batch.company),
            entry_mode=OpeningBalanceVoucher.EntryMode.BULK_IMPORT,
            opening_date=op_date,
            bs_date=bs_str,
            currency=batch.company.base_currency,
            exchange_rate=Decimal("1.000000"),
            source_entity_type="OpeningBalanceImport",
            source_entity_id=str(batch.id),
            migration_override_reason=migration_override_reason,
            status=OpeningBalanceVoucher.Status.DRAFT,
            total_debit=max(total_dr, total_cr),
            total_credit=max(total_dr, total_cr),
            narration=f"Bulk Opening Balance Import — {batch.batch_name}",
            prepared_by=user,
        )

        for idx, r in enumerate(rows, start=1):
            acc = acc_map[r.account_code]
            party = party_map.get(r.party_code) if r.party_code else None
            req_dir = DirectionChoice.DR if r.debit > 0 else DirectionChoice.CR
            amt = r.debit if r.debit > 0 else r.credit
            resolved = OpeningBalanceDirectionService.resolve_account_and_direction(
                company=batch.company,
                user=user,
                account=acc,
                party=party,
                requested_direction=req_dir,
                override_reason=f"Bulk import row #{r.row_no}" if req_dir else "",
            )
            adj_acc = OpeningBalanceMappingService.get_adjustment_account(company=batch.company, category=resolved["opening_category"])
            OpeningBalanceLine.objects.create(
                ob_voucher=ob,
                line_no=idx,
                account=resolved["account"],
                party=party,
                opening_category=resolved["opening_category"],
                direction=resolved["direction"],
                default_direction=resolved["default_direction"],
                is_direction_overridden=resolved["is_direction_overridden"],
                override_reason=resolved["override_reason"],
                amount=amt,
                debit=r.debit,
                credit=r.credit,
                currency=r.currency,
                exchange_rate=Decimal("1.000000"),
                base_debit=r.debit,
                base_credit=r.credit,
                adjustment_account=adj_acc,
                reference_no=r.reference_no,
                invoice_date=r.opening_date or op_date,
                due_date=r.due_date or (op_date + timedelta(days=30)),
                narration=f"Import #{r.row_no}: {resolved['account'].name}",
            )

        batch.status = "CONVERTED"
        batch.ob_voucher = ob
        batch.save(update_fields=["status", "ob_voucher"])
        if auto_post:
            ob = OpeningBalanceVoucherService.submit_approve_and_post(ob=ob, user=user)
        return ob


# ---------------------------------------------------------------------------
# 7. Reconciliation, Summary Table, Comprehensive Reports & Exports
# ---------------------------------------------------------------------------


class OpeningBalanceReconciliationService:
    """Reconciles Bank statements, Cash counts, AR/AP subledgers, Clearing Equity, and serves 20 Reports."""

    @staticmethod
    def reconcile_bank_opening(
        *,
        company,
        user,
        bank_account: BankAccount,
        statement_opening_balance: Decimal,
        reconciliation_date: date,
        deposits_in_transit: Decimal = Decimal("0.00"),
        unpresented_cheques: Decimal = Decimal("0.00"),
        explanation: str = "",
        evidence_ref: str = "",
    ) -> OpeningBalanceReconciliation:
        agg = LedgerEntry.objects.filter(
            company=company, account=bank_account.gl_account, voucher__voucher_type=Voucher.VoucherType.OPENING_BALANCE
        ).aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
        book_bal = (bank_account.gl_account.opening_debit - bank_account.gl_account.opening_credit) + (
            (agg["d"] or Decimal("0.00")) - (agg["c"] or Decimal("0.00"))
        )
        stmt_bal = _q2(statement_opening_balance)
        dep = _q2(deposits_in_transit)
        unp = _q2(unpresented_cheques)
        adjusted_stmt = stmt_bal + dep - unp
        variance = book_bal - adjusted_stmt

        fy = _active_fiscal_year(company, as_of=reconciliation_date)
        rec = OpeningBalanceReconciliation.objects.create(
            company=company,
            fiscal_year=fy,
            reconciliation_date=reconciliation_date,
            recon_kind="BANK_OPENING",
            reference_label=f"{bank_account.account_name} ({bank_account.gl_account.code})",
            book_balance=book_bal,
            external_balance=stmt_bal,
            deposits_in_transit=dep,
            unpresented_cheques=unp,
            variance_amount=variance,
            status="RECONCILED" if variance == Decimal("0.00") else "VARIANCE_OPEN",
            explanation=explanation,
            evidence_ref=evidence_ref,
            reconciled_by=user,
        )
        BankReconciliationSession.objects.create(
            company=company,
            bank_account=bank_account,
            period_start=reconciliation_date,
            period_end=reconciliation_date,
            statement_closing_balance=stmt_bal,
            book_closing_balance=book_bal,
            deposits_in_transit=dep,
            outstanding_cheques=unp,
            unreconciled_difference=variance,
            is_opening_recon=True,
            status=BankReconciliationSession.Status.APPROVED if variance == Decimal("0.00") else BankReconciliationSession.Status.DRAFT,
            approved_by=user if variance == Decimal("0.00") else None,
            approved_at=timezone.now() if variance == Decimal("0.00") else None,
        )
        return rec

    @staticmethod
    def reconcile_cash_physical(
        *,
        company,
        user,
        cash_account: CashAccount,
        physical_count_balance: Decimal,
        reconciliation_date: date,
        explanation: str = "",
        evidence_ref: str = "",
    ) -> OpeningBalanceReconciliation:
        agg = LedgerEntry.objects.filter(
            company=company, account=cash_account.gl_account, voucher__voucher_type=Voucher.VoucherType.OPENING_BALANCE
        ).aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
        book_bal = (cash_account.gl_account.opening_debit - cash_account.gl_account.opening_credit) + (
            (agg["d"] or Decimal("0.00")) - (agg["c"] or Decimal("0.00"))
        )
        phys_bal = _q2(physical_count_balance)
        variance = book_bal - phys_bal
        fy = _active_fiscal_year(company, as_of=reconciliation_date)
        return OpeningBalanceReconciliation.objects.create(
            company=company,
            fiscal_year=fy,
            reconciliation_date=reconciliation_date,
            recon_kind="CASH_PHYSICAL",
            reference_label=f"{cash_account.name} ({cash_account.gl_account.code})",
            book_balance=book_bal,
            external_balance=phys_bal,
            variance_amount=variance,
            status="RECONCILED" if variance == Decimal("0.00") else "VARIANCE_OPEN",
            explanation=explanation,
            evidence_ref=evidence_ref,
            reconciled_by=user,
        )

    @staticmethod
    def reconcile_subledgers_and_clearing(*, company) -> dict[str, Any]:
        ob_entries = LedgerEntry.objects.select_related("account").filter(
            company=company, voucher__voucher_type=Voucher.VoucherType.OPENING_BALANCE
        )
        # AR control GL vs Opening OpenItem RECEIVABLE
        ar_gl_agg = ob_entries.filter(account__control_role=Account.ControlRole.SUNDRY_DEBTORS).aggregate(
            d=Sum("base_debit"), c=Sum("base_credit")
        )
        ar_gl = (ar_gl_agg["d"] or Decimal("0.00")) - (ar_gl_agg["c"] or Decimal("0.00"))
        ar_sub_agg = OpenItem.objects.filter(
            company=company, hub_side=OpenItem.HubSide.RECEIVABLE, voucher__voucher_type=Voucher.VoucherType.OPENING_BALANCE, is_unallocated_credit=False
        ).exclude(status=OpenItem.Status.REVERSED).aggregate(s=Sum("original_amount"))
        ar_sub = ar_sub_agg["s"] or Decimal("0.00")

        # AP control GL vs Opening OpenItem PAYABLE
        ap_gl_agg = ob_entries.filter(
            account__control_role__in=[Account.ControlRole.SUNDRY_CREDITORS, Account.ControlRole.SUBCONTRACTOR_PAYABLE]
        ).aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
        ap_gl = (ap_gl_agg["c"] or Decimal("0.00")) - (ap_gl_agg["d"] or Decimal("0.00"))
        ap_sub_agg = OpenItem.objects.filter(
            company=company, hub_side=OpenItem.HubSide.PAYABLE, voucher__voucher_type=Voucher.VoucherType.OPENING_BALANCE, is_unallocated_credit=False
        ).exclude(status=OpenItem.Status.REVERSED).aggregate(s=Sum("original_amount"))
        ap_sub = ap_sub_agg["s"] or Decimal("0.00")

        # Clearing Equity Accounts (3900xx)
        clearing_agg = ob_entries.filter(account__code__startswith="3900").aggregate(d=Sum("base_debit"), c=Sum("base_credit"))
        clearing_net = (clearing_agg["c"] or Decimal("0.00")) - (clearing_agg["d"] or Decimal("0.00"))

        return {
            "ar_control_gl": str(ar_gl),
            "ar_subledger_sum": str(ar_sub),
            "ar_variance": str(ar_gl - ar_sub),
            "ap_control_gl": str(ap_gl),
            "ap_subledger_sum": str(ap_sub),
            "ap_variance": str(ap_gl - ap_sub),
            "clearing_net_credit": str(clearing_net),
            "is_clearing_zero": clearing_net == Decimal("0.00"),
            "is_fully_reconciled": (ar_gl - ar_sub == 0) and (ap_gl - ap_sub == 0) and (clearing_net == 0),
        }

    @staticmethod
    def get_summary_dashboard(*, company) -> dict[str, Any]:
        fy = _active_fiscal_year(company)
        profile = OpeningBalanceValidationService.get_or_create_profile(company=company)
        posted_lines = OpeningBalanceLine.objects.select_related("ob_voucher", "account").filter(
            ob_voucher__company=company,
            ob_voucher__status=OpeningBalanceVoucher.Status.POSTED,
        )
        cat_totals: dict[str, dict[str, Any]] = {}
        total_dr = Decimal("0.00")
        total_cr = Decimal("0.00")
        for line in posted_lines:
            cat = line.opening_category
            if cat not in cat_totals:
                cat_totals[cat] = {"category": cat, "label": cat.replace("_", " ").title(), "debit": Decimal("0.00"), "credit": Decimal("0.00"), "count": 0}
            cat_totals[cat]["debit"] += line.base_debit
            cat_totals[cat]["credit"] += line.base_credit
            cat_totals[cat]["count"] += 1
            total_dr += line.base_debit
            total_cr += line.base_credit

        recon = OpeningBalanceReconciliationService.reconcile_subledgers_and_clearing(company=company)
        v_qs = OpeningBalanceVoucher.objects.filter(company=company)
        return {
            "fiscal_year": fy.name,
            "conversion_cutoff_date": profile.conversion_cutoff_date.isoformat(),
            "bs_cutoff_date": profile.bs_cutoff_date,
            "is_migration_locked": profile.is_migration_locked,
            "require_approval": profile.require_approval,
            "totals": {
                "total_debit": str(total_dr),
                "total_credit": str(total_cr),
                "net_difference": str(total_dr - total_cr),
                "clearing_balance": recon["clearing_net_credit"],
            },
            "status_counts": {
                "draft": v_qs.filter(status=OpeningBalanceVoucher.Status.DRAFT).count(),
                "submitted": v_qs.filter(status=OpeningBalanceVoucher.Status.SUBMITTED).count(),
                "approved": v_qs.filter(status=OpeningBalanceVoucher.Status.APPROVED).count(),
                "posted": v_qs.filter(status=OpeningBalanceVoucher.Status.POSTED).count(),
                "reversed": v_qs.filter(status=OpeningBalanceVoucher.Status.REVERSED).count(),
            },
            "categories": [
                {**v, "debit": str(v["debit"]), "credit": str(v["credit"]), "net": str(v["debit"] - v["credit"])}
                for v in sorted(cat_totals.values(), key=lambda x: x["category"])
            ],
            "reconciliation": recon,
        }

    @staticmethod
    def get_report(*, company, report_key: str) -> dict[str, Any]:
        rk = (report_key or "summary").upper()
        lines_qs = OpeningBalanceLine.objects.select_related("ob_voucher", "account", "party", "adjustment_account").filter(
            ob_voucher__company=company, ob_voucher__status=OpeningBalanceVoucher.Status.POSTED
        )

        CATEGORY_FILTER = {
            "BANK_OPENING": [OpeningCategory.BANK],
            "CASH_OPENING": [OpeningCategory.CASH],
            "AR_BILLWISE": [OpeningCategory.DEBTORS],
            "AP_BILLWISE": [OpeningCategory.CREDITORS],
            "ADVANCES": [OpeningCategory.EMPLOYEE_ADVANCES, OpeningCategory.SUPPLIER_ADVANCES, OpeningCategory.CUSTOMER_ADVANCES],
            "LOANS_OD": [OpeningCategory.LOANS, OpeningCategory.OD_CC],
            "INVENTORY": [OpeningCategory.INVENTORY],
            "FIXED_ASSETS": [OpeningCategory.FIXED_ASSETS, OpeningCategory.ACCUM_DEPRECIATION],
            "RETENTION": [OpeningCategory.RETENTION_RECEIVABLE, OpeningCategory.RETENTION_PAYABLE],
            "TAX_STATUTORY": [OpeningCategory.TAX_RECEIVABLE, OpeningCategory.TAX_PAYABLE],
        }

        if rk in CATEGORY_FILTER:
            cats = CATEGORY_FILTER[rk]
            rows = [
                {
                    "ob_number": l.ob_voucher.ob_number,
                    "opening_date": l.ob_voucher.opening_date.isoformat(),
                    "bs_date": l.ob_voucher.bs_date,
                    "account_code": l.account.code,
                    "account_name": l.account.name,
                    "party": l.party.name if l.party else "",
                    "reference_no": l.reference_no,
                    "due_date": l.due_date.isoformat() if l.due_date else "",
                    "direction": l.direction,
                    "debit": str(l.base_debit),
                    "credit": str(l.base_credit),
                    "adjustment_account": f"{l.adjustment_account.code} — {l.adjustment_account.name}",
                }
                for l in lines_qs.filter(opening_category__in=cats)
            ]
            return {"report_key": rk, "rows": rows}
        elif rk == "DIRECTION_OVERRIDES":
            rows = [
                {
                    "ob_number": l.ob_voucher.ob_number,
                    "account": f"{l.account.code} — {l.account.name}",
                    "default_direction": l.default_direction,
                    "direction": l.direction,
                    "amount": str(l.amount),
                    "override_reason": l.override_reason,
                }
                for l in lines_qs.filter(is_direction_overridden=True)
            ]
            return {"report_key": rk, "rows": rows}
        elif rk == "CORRECTIONS":
            rows = [
                {
                    "original_ob": c.original_ob_voucher.ob_number,
                    "reversal_ob": c.reversal_ob_voucher.ob_number if c.reversal_ob_voucher else "",
                    "replacement_ob": c.replacement_ob_voucher.ob_number if c.replacement_ob_voucher else "",
                    "correction_type": c.correction_type,
                    "original_amount": f"{c.original_amount} {c.original_direction}",
                    "corrected_amount": f"{c.corrected_amount} {c.corrected_direction}",
                    "reason": c.reason,
                    "created_at": c.created_at.isoformat(),
                }
                for c in OpeningBalanceCorrection.objects.filter(company=company).select_related("original_ob_voucher", "reversal_ob_voucher", "replacement_ob_voucher")
            ]
            return {"report_key": rk, "rows": rows}
        elif rk == "AUDIT_TRAIL":
            rows = [
                {
                    "action": e.action,
                    "entity_type": e.entity_type,
                    "entity_id": e.entity_id,
                    "actor": e.actor.username if e.actor else "System",
                    "notes": e.notes,
                    "created_at": e.created_at.isoformat(),
                }
                for e in OpeningBalanceAuditEvent.objects.filter(company=company).select_related("actor")[:200]
            ]
            return {"report_key": rk, "rows": rows}
        elif rk == "RECONCILIATIONS":
            rows = [
                {
                    "date": r.reconciliation_date.isoformat(),
                    "kind": r.recon_kind,
                    "reference": r.reference_label,
                    "book_balance": str(r.book_balance),
                    "external_balance": str(r.external_balance),
                    "variance": str(r.variance_amount),
                    "status": r.status,
                }
                for r in OpeningBalanceReconciliation.objects.filter(company=company)
            ]
            return {"report_key": rk, "rows": rows}
        elif rk == "CARRY_FORWARD":
            rows = [
                {
                    "source_fy": c.source_fiscal_year.name,
                    "target_fy": c.target_fiscal_year.name,
                    "date": c.carry_forward_date.isoformat(),
                    "ob_number": c.ob_voucher.ob_number,
                    "total_debit": str(c.total_debit),
                    "total_credit": str(c.total_credit),
                    "accounts_carried": c.accounts_carried,
                    "open_items_carried": c.open_items_carried,
                }
                for c in FinancialYearOpeningCarryForward.objects.filter(company=company).select_related("source_fiscal_year", "target_fiscal_year", "ob_voucher")
            ]
            return {"report_key": rk, "rows": rows}

        # Default SUMMARY / REGISTER
        summary = OpeningBalanceReconciliationService.get_summary_dashboard(company=company)
        return {"report_key": rk, "summary": summary, "rows": summary["categories"]}

    @staticmethod
    def export_report_bytes(*, company, report_key: str, fmt: str = "CSV") -> tuple[bytes, str, str]:
        data = OpeningBalanceReconciliationService.get_report(company=company, report_key=report_key)
        rows = data.get("rows") or []
        f_upper = fmt.upper()
        headers = list(rows[0].keys()) if rows else ["message"]
        if not rows:
            rows = [{"message": "No opening balance records found"}]

        if f_upper == "XLSX":
            import openpyxl
            wb = openpyxl.Workbook()
            ws = wb.active
            ws.title = report_key[:28]
            ws.append(headers)
            for row in rows:
                ws.append([str(row.get(h, "")) for h in headers])
            buf = io.BytesIO()
            wb.save(buf)
            return buf.getvalue(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", f"{report_key.lower()}.xlsx"

        if f_upper == "PDF":
            try:
                from reportlab.lib.pagesizes import A4, landscape
                from reportlab.pdfgen import canvas

                buf = io.BytesIO()
                c = canvas.Canvas(buf, pagesize=landscape(A4))
                c.setFont("Helvetica-Bold", 13)
                c.drawString(30, 560, f"Maya OS Opening Balance Report — {report_key}")
                y = 535
                c.setFont("Helvetica", 8)
                c.drawString(30, y, " | ".join(headers))
                y -= 14
                for row in rows[:40]:
                    line = " | ".join(str(row.get(h, ""))[:22] for h in headers)
                    c.drawString(30, y, line)
                    y -= 12
                    if y < 40:
                        c.showPage()
                        y = 550
                c.save()
                return buf.getvalue(), "application/pdf", f"{report_key.lower()}.pdf"
            except Exception:
                pass  # fallback to CSV if reportlab absent

        out = io.StringIO()
        writer = csv.DictWriter(out, fieldnames=headers)
        writer.writeheader()
        for row in rows:
            writer.writerow({h: row.get(h, "") for h in headers})
        return out.getvalue().encode("utf-8"), "text/csv; charset=utf-8", f"{report_key.lower()}.csv"


# ---------------------------------------------------------------------------
# 8. Audit-Safe Reversal & Correction Service (Immutability Enforced)
# ---------------------------------------------------------------------------


class OpeningBalanceCorrectionService:
    """Reverses a posted OpeningBalanceVoucher via PostingService and optionally posts a replacement."""

    @staticmethod
    @transaction.atomic
    def correct_posted_opening(
        *,
        ob: OpeningBalanceVoucher,
        user,
        reason: str,
        correction_type: str = "AMOUNT_OR_DIRECTION",
        corrected_amount: Decimal | None = None,
        corrected_direction: str = "",
        supporting_doc_ref: str = "",
        auto_post_replacement: bool = True,
    ) -> OpeningBalanceCorrection:
        if not _has_perm(ob.company, user, Permissions.OPENING_BALANCE_REVERSE):
            raise ValidationError(f"Permission '{Permissions.OPENING_BALANCE_REVERSE}' is required to reverse/correct opening balances.")
        if ob.status != OpeningBalanceVoucher.Status.POSTED or not ob.voucher_id:
            raise ValidationError("Only POSTED opening balance vouchers require reversal/correction.")
        if not (reason or "").strip():
            raise ValidationError("A detailed reason is required to reverse and correct a posted opening balance.")

        first_line = ob.lines.select_related("account", "party", "project", "adjustment_account").first()
        if not first_line:
            raise ValidationError("Original opening voucher has no lines.")

        # 1. Reverse underlying posted Voucher atomically through PostingService
        rev_gl = PostingService.reverse_voucher(
            voucher=ob.voucher,
            user=user,
            reason=f"OB Correction: {reason}",
            reversal_date=ob.opening_date,
        )
        rev_ob = OpeningBalanceVoucher.objects.create(
            company=ob.company,
            fiscal_year=ob.fiscal_year,
            ob_number=_next_ob_number(ob.company),
            entry_mode=ob.entry_mode,
            opening_date=ob.opening_date,
            bs_date=ob.bs_date,
            currency=ob.currency,
            exchange_rate=ob.exchange_rate,
            source_entity_type=ob.source_entity_type,
            source_entity_id=ob.source_entity_id,
            status=OpeningBalanceVoucher.Status.REVERSED,
            voucher=rev_gl,
            total_debit=ob.total_debit,
            total_credit=ob.total_credit,
            supporting_doc_ref=supporting_doc_ref,
            narration=f"Reversal of {ob.ob_number}: {reason}",
            prepared_by=user,
            approved_by=user,
            posted_by=user,
            approved_at=timezone.now(),
            posted_at=timezone.now(),
        )
        ob.status = OpeningBalanceVoucher.Status.REVERSED
        ob.save(update_fields=["status", "updated_at"])

        # Clear party references tied to reversed OB so replacement can reuse invoice_ref cleanly
        OpeningBalancePartyReference.objects.filter(company=ob.company, ob_voucher=ob).delete()

        # 2. Create replacement OpeningBalanceVoucher if corrected_amount > 0
        new_amt = _q2(corrected_amount if corrected_amount is not None else first_line.amount)
        new_dir = (corrected_direction or first_line.direction).upper()
        repl_ob = None
        if new_amt > Decimal("0.00"):
            repl_ob = OpeningBalanceCreationService.create_single_account_opening(
                company=ob.company,
                user=user,
                account=first_line.account,
                amount=new_amt,
                opening_date=ob.opening_date,
                bs_date=ob.bs_date,
                direction=new_dir,
                adjustment_account=first_line.adjustment_account,
                party=first_line.party,
                project=first_line.project,
                category=first_line.opening_category,
                currency=ob.currency,
                exchange_rate=ob.exchange_rate,
                source_entity_type=ob.source_entity_type,
                source_entity_id=ob.source_entity_id,
                reference_no=first_line.reference_no or supporting_doc_ref,
                narration=f"Corrected replacement for {ob.ob_number}: {reason}",
                override_reason=reason if new_dir != first_line.default_direction else "",
                migration_override_reason=ob.migration_override_reason or reason,
                auto_post=auto_post_replacement,
            )

        corr = OpeningBalanceCorrection.objects.create(
            company=ob.company,
            original_ob_voucher=ob,
            reversal_ob_voucher=rev_ob,
            replacement_ob_voucher=repl_ob,
            correction_type=correction_type,
            original_amount=first_line.amount,
            original_direction=first_line.direction,
            corrected_amount=new_amt,
            corrected_direction=new_dir,
            reason=reason,
            supporting_doc_ref=supporting_doc_ref,
            approved_by=user,
        )
        _audit_ob(
            company=ob.company,
            action="OB_CORRECTED",
            entity_type="OpeningBalanceCorrection",
            entity_id=str(corr.id),
            actor=user,
            prev={"ob_number": ob.ob_number, "amount": str(first_line.amount), "direction": first_line.direction},
            new={"replacement": repl_ob.ob_number if repl_ob else "NONE", "amount": str(new_amt), "direction": new_dir},
            notes=reason,
        )
        return corr


# ---------------------------------------------------------------------------
# 9. Financial Year End Carry-Forward Service
# ---------------------------------------------------------------------------


class FinancialYearCarryForwardService:
    """Carries closing Balance Sheet, Retained Earnings (Net P&L), and Open Items to the next Fiscal Year."""

    @staticmethod
    @transaction.atomic
    def execute_carry_forward(
        *,
        company,
        user,
        source_fiscal_year: FiscalYear,
        target_fiscal_year: FiscalYear,
        retained_earnings_account: Account | None = None,
    ) -> FinancialYearOpeningCarryForward:
        if not _has_perm(company, user, Permissions.OPENING_BALANCE_CARRY_FORWARD):
            raise ValidationError(f"Permission '{Permissions.OPENING_BALANCE_CARRY_FORWARD}' is required.")
        if source_fiscal_year.id == target_fiscal_year.id:
            raise ValidationError("Source and Target Fiscal Years must be distinct.")
        if FinancialYearOpeningCarryForward.objects.filter(
            company=company, source_fiscal_year=source_fiscal_year, target_fiscal_year=target_fiscal_year
        ).exists():
            raise ValidationError(
                f"Carry-forward from {source_fiscal_year.name} to {target_fiscal_year.name} has already been executed."
            )

        OpeningBalanceMappingService.ensure_default_adjustment_accounts(company=company, fiscal_year=target_fiscal_year)
        re_acc = retained_earnings_account or Account.objects.get(company=company, code="390012")
        clr_acc = Account.objects.get(company=company, code="390001")

        # Compute closing balances up to source_fiscal_year.end_date across all posted LedgerEntries
        entries_agg = {
            row["account_id"]: row
            for row in LedgerEntry.objects.filter(
                company=company, posting_date__lte=source_fiscal_year.end_date
            ).values("account_id").annotate(d=Sum("base_debit"), c=Sum("base_credit"))
        }

        accounts = Account.objects.filter(company=company, is_group=False, is_active=True).order_by("code")
        cf_lines: list[dict[str, Any]] = []
        net_pnl = Decimal("0.00")

        for acc in accounts:
            agg = entries_agg.get(acc.id, {})
            net = (acc.opening_debit - acc.opening_credit) + (
                (agg.get("d") or Decimal("0.00")) - (agg.get("c") or Decimal("0.00"))
            )
            if acc.account_type == Account.AccountType.INCOME:
                net_pnl -= net  # Income net is Cr positive -> P&L += (C - D)
                continue
            if acc.account_type == Account.AccountType.EXPENSE:
                net_pnl -= net  # Expense net is Dr positive -> P&L -= (D - C)
                continue
            if net == Decimal("0.00"):
                continue
            cf_lines.append({"account": acc, "net": net})

        if net_pnl != Decimal("0.00"):
            cf_lines.append({"account": re_acc, "net": -net_pnl})  # Cr positive if profit > 0

        if not cf_lines:
            raise ValidationError(f"No closing Balance Sheet balances found up to {source_fiscal_year.end_date} to carry forward.")

        carry_date = target_fiscal_year.start_date
        _, bs_str = OpeningBalanceValidationService.resolve_opening_dates(company=company, opening_date=carry_date)

        ob = OpeningBalanceVoucher.objects.create(
            company=company,
            fiscal_year=target_fiscal_year,
            ob_number=_next_ob_number(company),
            entry_mode=OpeningBalanceVoucher.EntryMode.CARRY_FORWARD,
            opening_date=carry_date,
            bs_date=bs_str,
            currency=company.base_currency,
            exchange_rate=Decimal("1.000000"),
            source_entity_type="FinancialYear",
            source_entity_id=str(source_fiscal_year.id),
            is_historical_migration=False,
            status=OpeningBalanceVoucher.Status.APPROVED,
            supporting_doc_ref=f"CF-{source_fiscal_year.name}->{target_fiscal_year.name}",
            narration=f"Year-End Opening Balance Carry-Forward from FY {source_fiscal_year.name} to FY {target_fiscal_year.name}",
            prepared_by=user,
            approved_by=user,
            approved_at=timezone.now(),
        )

        total_dr = Decimal("0.00")
        total_cr = Decimal("0.00")
        for idx, item in enumerate(cf_lines, start=1):
            acc = item["account"]
            net = _q2(item["net"])
            dr = net if net > 0 else Decimal("0.00")
            cr = -net if net < 0 else Decimal("0.00")
            total_dr += dr
            total_cr += cr
            info = OpeningBalanceDirectionService.get_default_direction(account=acc)
            eff_dir = DirectionChoice.DR if dr > 0 else DirectionChoice.CR
            OpeningBalanceLine.objects.create(
                ob_voucher=ob,
                line_no=idx,
                account=acc,
                opening_category=info["opening_category"],
                direction=eff_dir,
                default_direction=info["default_direction"],
                is_direction_overridden=eff_dir != info["default_direction"],
                override_reason="Closing carry-forward balance",
                amount=abs(net),
                debit=dr,
                credit=cr,
                currency=company.base_currency,
                exchange_rate=Decimal("1.000000"),
                base_debit=dr,
                base_credit=cr,
                adjustment_account=clr_acc,
                reference_no=f"CF-{acc.code}",
                narration=f"Carried from FY {source_fiscal_year.name}",
            )

        ob.total_debit = total_dr
        ob.total_credit = total_cr
        ob.save(update_fields=["total_debit", "total_credit"])

        OpeningBalancePostingService.post_ob_voucher(ob=ob, user=user, bypass_perm_check=True)

        open_items_cnt = OpenItem.objects.filter(
            company=company, document_date__lte=source_fiscal_year.end_date, status__in=[OpenItem.Status.OPEN, OpenItem.Status.PARTIAL]
        ).count()

        cf_rec = FinancialYearOpeningCarryForward.objects.create(
            company=company,
            source_fiscal_year=source_fiscal_year,
            target_fiscal_year=target_fiscal_year,
            carry_forward_date=carry_date,
            ob_voucher=ob,
            total_debit=total_dr,
            total_credit=total_cr,
            accounts_carried=len(cf_lines),
            open_items_carried=open_items_cnt,
            status="POSTED",
            executed_by=user,
        )
        _audit_ob(
            company=company,
            action="FY_CARRY_FORWARD_EXECUTED",
            entity_type="FinancialYearOpeningCarryForward",
            entity_id=str(cf_rec.id),
            actor=user,
            new_state={"source": source_fiscal_year.name, "target": target_fiscal_year.name, "ob_number": ob.ob_number},
        )
        return cf_rec

