import calendar
import hashlib
import json
from datetime import date, datetime, time, timedelta
from decimal import Decimal, ROUND_HALF_UP

from django.core.serializers.json import DjangoJSONEncoder
from django.db import IntegrityError, transaction
from django.db.models import Q, Sum
from django.utils import timezone

from economy.models import LedgerEntry, Wallet
from .constants import (
    AccrualDocumentType,
    AccrualStatus,
    GLAccountType,
    GLCode,
    GLNormalBalance,
    JournalStatus,
    StatementType,
)
from .models import (
    AccountingPeriod,
    AccrualDocument,
    AccrualSettlement,
    FinancialControlEvent,
    FinancialStatementSnapshot,
    FixedAssetBook,
    GLAccount,
    JournalEntry,
    JournalLine,
    PlayerRegistrationAsset,
)
from .exceptions import BudgetIntegrityError

Q8 = Decimal("0.00000001")
ZERO = Decimal("0")


def q8(value):
    return Decimal(value or 0).quantize(Q8, rounding=ROUND_HALF_UP)


def _hash(payload):
    raw = json.dumps(payload, cls=DjangoJSONEncoder, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(raw).hexdigest()


def _as_date(value):
    if hasattr(value, "date") and not isinstance(value, date):
        return value.date()
    return value


def _add_months(d, months):
    month0 = d.month - 1 + int(months)
    year = d.year + month0 // 12
    month = month0 % 12 + 1
    day = min(d.day, calendar.monthrange(year, month)[1])
    return date(year, month, day)


DEFAULT_CHART = [
    (GLCode.CASH, "Cash / Club treasury", GLAccountType.ASSET, GLNormalBalance.DEBIT, True),
    (GLCode.MARKETPLACE_DEPOSIT, "Marketplace escrow and refundable deposits", GLAccountType.ASSET, GLNormalBalance.DEBIT, True),
    (GLCode.ACCOUNTS_RECEIVABLE, "Accounts receivable", GLAccountType.ASSET, GLNormalBalance.DEBIT, True),
    (GLCode.PREPAID_EXPENSES, "Prepaid expenses", GLAccountType.ASSET, GLNormalBalance.DEBIT, False),
    (GLCode.PLAYER_REGISTRATION_ASSET, "Player registration rights", GLAccountType.ASSET, GLNormalBalance.DEBIT, True),
    (GLCode.CLUB_FACILITIES, "Stadium and training-ground assets", GLAccountType.ASSET, GLNormalBalance.DEBIT, True),
    (GLCode.ACCUMULATED_DEPRECIATION, "Accumulated depreciation - facilities", GLAccountType.ASSET, GLNormalBalance.CREDIT, True),
    (GLCode.OTHER_NFT_ASSETS, "Other NFT / utility assets", GLAccountType.ASSET, GLNormalBalance.DEBIT, False),
    (GLCode.OTHER_CURRENT_ASSET, "Other current assets / suspense", GLAccountType.ASSET, GLNormalBalance.DEBIT, False),
    (GLCode.ACCOUNTS_PAYABLE, "Accounts payable", GLAccountType.LIABILITY, GLNormalBalance.CREDIT, True),
    (GLCode.PAYROLL_PAYABLE, "Payroll payable", GLAccountType.LIABILITY, GLNormalBalance.CREDIT, True),
    (GLCode.ACCRUED_EXPENSES, "Accrued expenses", GLAccountType.LIABILITY, GLNormalBalance.CREDIT, True),
    (GLCode.LOANS_PAYABLE, "Loans payable", GLAccountType.LIABILITY, GLNormalBalance.CREDIT, True),
    (GLCode.DEFERRED_REVENUE, "Deferred / unearned revenue", GLAccountType.LIABILITY, GLNormalBalance.CREDIT, True),
    (GLCode.OTHER_CURRENT_LIABILITY, "Other current liabilities / suspense", GLAccountType.LIABILITY, GLNormalBalance.CREDIT, False),
    (GLCode.OWNER_CAPITAL, "Owner capital / external funding", GLAccountType.EQUITY, GLNormalBalance.CREDIT, True),
    (GLCode.OPENING_EQUITY, "Opening balance equity", GLAccountType.EQUITY, GLNormalBalance.CREDIT, True),
    (GLCode.RETAINED_EARNINGS, "Retained earnings", GLAccountType.EQUITY, GLNormalBalance.CREDIT, True),
    (GLCode.OWNER_DRAWS, "Owner distributions", GLAccountType.EQUITY, GLNormalBalance.DEBIT, False),
    (GLCode.MATCHDAY_REVENUE, "Matchday revenue", GLAccountType.REVENUE, GLNormalBalance.CREDIT, False),
    (GLCode.COMMERCIAL_REVENUE, "Commercial revenue", GLAccountType.REVENUE, GLNormalBalance.CREDIT, False),
    (GLCode.SPONSORSHIP_REVENUE, "Sponsorship revenue", GLAccountType.REVENUE, GLNormalBalance.CREDIT, False),
    (GLCode.TRANSFER_REVENUE, "Player transfer and loan-fee revenue", GLAccountType.REVENUE, GLNormalBalance.CREDIT, False),
    (GLCode.ASSET_SALE_PROCEEDS, "Asset sale proceeds", GLAccountType.REVENUE, GLNormalBalance.CREDIT, False),
    (GLCode.PRIZE_REVENUE, "Prize and performance revenue", GLAccountType.REVENUE, GLNormalBalance.CREDIT, False),
    (GLCode.OTHER_REVENUE, "Other revenue", GLAccountType.REVENUE, GLNormalBalance.CREDIT, False),
    (GLCode.PLAYER_WAGES, "Player wages", GLAccountType.EXPENSE, GLNormalBalance.DEBIT, False),
    (GLCode.STAFF_WAGES, "Staff wages", GLAccountType.EXPENSE, GLNormalBalance.DEBIT, False),
    (GLCode.PAYROLL_BONUS, "Payroll and performance bonuses", GLAccountType.EXPENSE, GLNormalBalance.DEBIT, False),
    (GLCode.SIGNING_BONUS, "Signing bonuses", GLAccountType.EXPENSE, GLNormalBalance.DEBIT, False),
    (GLCode.TERMINATION_COMPENSATION, "Termination compensation", GLAccountType.EXPENSE, GLNormalBalance.DEBIT, False),
    (GLCode.FACILITY_OPEX, "Facility and matchday operating costs", GLAccountType.EXPENSE, GLNormalBalance.DEBIT, False),
    (GLCode.TRAINING_OPEX, "Training expense", GLAccountType.EXPENSE, GLNormalBalance.DEBIT, False),
    (GLCode.NUTRITION_OPEX, "Nutrition expense", GLAccountType.EXPENSE, GLNormalBalance.DEBIT, False),
    (GLCode.FEDERATION_FEES, "Federation / registration fees", GLAccountType.EXPENSE, GLNormalBalance.DEBIT, False),
    (GLCode.FINES, "Fines", GLAccountType.EXPENSE, GLNormalBalance.DEBIT, False),
    (GLCode.PLAYER_LOAN_EXPENSE, "Player loan fees", GLAccountType.EXPENSE, GLNormalBalance.DEBIT, False),
    (GLCode.ASSET_DISPOSAL_COST, "Carrying value of disposed assets", GLAccountType.EXPENSE, GLNormalBalance.DEBIT, False),
    (GLCode.DEBT_INTEREST, "Debt interest", GLAccountType.EXPENSE, GLNormalBalance.DEBIT, False),
    (GLCode.DEBT_FEES, "Debt fees and penalties", GLAccountType.EXPENSE, GLNormalBalance.DEBIT, False),
    (GLCode.DEPRECIATION_EXPENSE, "Depreciation expense", GLAccountType.EXPENSE, GLNormalBalance.DEBIT, False),
    (GLCode.PLAYER_AMORTIZATION_EXPENSE, "Player registration amortization", GLAccountType.EXPENSE, GLNormalBalance.DEBIT, False),
    (GLCode.MARKETPLACE_FEES, "Marketplace transaction fees", GLAccountType.EXPENSE, GLNormalBalance.DEBIT, False),
    (GLCode.OTHER_EXPENSE, "Other operating expense", GLAccountType.EXPENSE, GLNormalBalance.DEBIT, False),
]


class ChartOfAccountsService:
    @classmethod
    @transaction.atomic
    def ensure_defaults(cls, club):
        created = 0
        for code, name, account_type, normal, control in DEFAULT_CHART:
            _, was_created = GLAccount.objects.get_or_create(
                club=club,
                code=code,
                defaults={
                    "name": name,
                    "account_type": account_type,
                    "normal_balance": normal,
                    "is_system": True,
                    "is_control_account": control,
                    "allow_manual_entries": False,
                },
            )
            created += int(was_created)
        return {"created": created, "total": GLAccount.objects.filter(club=club).count()}

    @staticmethod
    def account(club, code):
        return GLAccount.objects.get(club=club, code=code, is_active=True)


class JournalService:
    @staticmethod
    def _period_for(club, accounting_date):
        tz = timezone.get_current_timezone()
        start = timezone.make_aware(datetime.combine(accounting_date, time.min), tz)
        end = timezone.make_aware(datetime.combine(accounting_date + timedelta(days=1), time.min), tz)
        return AccountingPeriod.objects.filter(
            club=club, starts_at__lt=end, ends_at__gt=start
        ).order_by("-starts_at").first()

    @classmethod
    @transaction.atomic
    def post(cls, *, club, accounting_date, source_type, source_id="", lines,
             idempotency_key, memo="", economy_ledger=None, period=None):
        accounting_date = _as_date(accounting_date)
        existing = JournalEntry.objects.filter(idempotency_key=idempotency_key).prefetch_related("lines__account").first()
        period = period or (existing.period if existing else cls._period_for(club, accounting_date))
        if period is None:
            raise BudgetIntegrityError("No accounting period covers this journal date")
        period = AccountingPeriod.objects.select_for_update().get(pk=period.pk)
        if period.is_closed and existing is None:
            raise BudgetIntegrityError("Accounting period is closed")
        ChartOfAccountsService.ensure_defaults(club)
        normalized = []
        total_debit = ZERO
        total_credit = ZERO
        for index, item in enumerate(lines, 1):
            debit = q8(item.get("debit", 0))
            credit = q8(item.get("credit", 0))
            if (debit > 0) == (credit > 0):
                raise BudgetIntegrityError("Each journal line must contain exactly one positive debit or credit")
            account = ChartOfAccountsService.account(club, item["account"])
            total_debit += debit
            total_credit += credit
            normalized.append({
                "line_no": index,
                "account": account,
                "code": account.code,
                "debit": debit,
                "credit": credit,
                "description": item.get("description", ""),
                "metadata": item.get("metadata", {}),
            })
        if total_debit <= 0 or q8(total_debit) != q8(total_credit):
            raise BudgetIntegrityError("Journal entry is not balanced")
        legacy_payload = {
            "club": str(club.pk), "date": accounting_date.isoformat(), "source_type": source_type,
            "source_id": str(source_id or ""), "debit": str(q8(total_debit)), "credit": str(q8(total_credit)),
            "lines": [{"code": x["code"], "debit": str(x["debit"]), "credit": str(x["credit"])} for x in normalized],
        }
        payload = {
            **legacy_payload,
            "schema_version": 2,
            "lines": [
                {
                    "code": x["code"], "debit": str(x["debit"]), "credit": str(x["credit"]),
                    "description": x["description"], "metadata": x["metadata"],
                }
                for x in normalized
            ],
        }
        checksum = _hash(payload)
        legacy_checksum = _hash(legacy_payload)
        if existing:
            if existing.club_id != club.pk or existing.checksum not in {checksum, legacy_checksum}:
                raise BudgetIntegrityError("Journal idempotency key reused with different accounting semantics")
            from .regulatory_dimensions import GLRegulatoryClassificationService
            GLRegulatoryClassificationService.classify_entry(existing)
            return existing
        token = hashlib.sha256(idempotency_key.encode()).hexdigest()[:16].upper()
        try:
            with transaction.atomic():
                entry = JournalEntry.objects.create(
                    club=club, period=period, accounting_date=accounting_date,
                    journal_no=f"GL-{str(club.pk)[:8]}-{token}", status=JournalStatus.POSTED,
                    source_type=source_type, source_id=str(source_id or ""), economy_ledger=economy_ledger,
                    memo=memo, idempotency_key=idempotency_key, checksum=checksum,
                )
                JournalLine.objects.bulk_create([
                    JournalLine(
                        entry=entry, line_no=x["line_no"], account=x["account"], debit=x["debit"], credit=x["credit"],
                        description=x["description"], metadata=x["metadata"],
                    ) for x in normalized
                ])
        except IntegrityError:
            entry = JournalEntry.objects.select_for_update().get(idempotency_key=idempotency_key)
            if entry.club_id != club.pk or entry.checksum not in {checksum, legacy_checksum}:
                raise BudgetIntegrityError("Concurrent journal idempotency conflict")
            from .regulatory_dimensions import GLRegulatoryClassificationService
            GLRegulatoryClassificationService.classify_entry(entry)
            return entry
        from .regulatory_dimensions import GLRegulatoryClassificationService
        GLRegulatoryClassificationService.classify_entry(entry)
        from core_runtime.services import OutboxService
        OutboxService.enqueue(
            topic="club_finance.general_ledger", event_type="club_finance.journal.posted",
            aggregate_type="JournalEntry", aggregate_id=entry.pk,
            deduplication_key=f"gl-journal:{entry.pk}",
            payload={"club_id": str(club.pk), "journal_id": str(entry.pk), "journal_no": entry.journal_no,
                     "accounting_date": accounting_date.isoformat(), "source_type": source_type, "source_id": str(source_id or "")},
        )
        return entry

    @classmethod
    @transaction.atomic
    def reverse(cls, entry, *, accounting_date=None, reason=""):
        entry = JournalEntry.objects.select_for_update().prefetch_related("lines__account").get(pk=entry.pk)
        if entry.status == JournalStatus.REVERSED:
            return entry.reversal_entry
        accounting_date = accounting_date or timezone.localdate()
        lines = [{
            "account": line.account.code, "debit": line.credit, "credit": line.debit,
            "description": f"Reversal: {line.description}", "metadata": {"reversal_of_line": str(line.pk)},
        } for line in entry.lines.all()]
        reversal = cls.post(
            club=entry.club, accounting_date=accounting_date, source_type="JOURNAL_REVERSAL", source_id=str(entry.pk),
            lines=lines, idempotency_key=f"gl-reversal:{entry.pk}", memo=reason or f"Reversal of {entry.journal_no}",
        )
        reversal.reversal_of = entry
        reversal.save(update_fields=["reversal_of"])
        entry.status = JournalStatus.REVERSED
        entry.save(update_fields=["status"])
        return reversal


class AccrualAccountingService:
    @staticmethod
    def _payroll_expense_code(obligation):
        from club_payroll.constants import ObligationType, PayrollPlanType
        if obligation.obligation_type == ObligationType.TERMINATION:
            return GLCode.TERMINATION_COMPENSATION
        if obligation.obligation_type == ObligationType.BONUS:
            return GLCode.PAYROLL_BONUS
        if obligation.plan_id and obligation.plan.plan_type == PayrollPlanType.STAFF:
            return GLCode.STAFF_WAGES
        return GLCode.PLAYER_WAGES

    @classmethod
    @transaction.atomic
    def ensure_payroll_document(cls, obligation):
        from club_payroll.constants import ObligationStatus
        from club_payroll.models import PayrollObligation
        obligation = PayrollObligation.objects.select_for_update(of=("self",)).select_related("plan", "recipient_wallet").get(pk=obligation.pk)
        if obligation.status in [ObligationStatus.CANCELLED, ObligationStatus.WAIVED]:
            return None
        existing = AccrualDocument.objects.filter(
            club=obligation.club, document_type=AccrualDocumentType.PAYABLE,
            source_type="PAYROLL_OBLIGATION", source_id=str(obligation.pk),
        ).first()
        if existing:
            return existing
        ChartOfAccountsService.ensure_defaults(obligation.club)
        recognized_on = obligation.due_date
        period = JournalService._period_for(obligation.club, recognized_on)
        if period is None or period.is_closed:
            return None
        expense_code = cls._payroll_expense_code(obligation)
        journal = JournalService.post(
            club=obligation.club, period=period, accounting_date=recognized_on,
            source_type="PAYROLL_ACCRUAL", source_id=str(obligation.pk),
            idempotency_key=f"gl-payroll-accrual:{obligation.pk}",
            memo=obligation.description or "Payroll expense accrual",
            lines=[
                {"account": expense_code, "debit": obligation.original_amount, "credit": 0},
                {"account": GLCode.PAYROLL_PAYABLE, "debit": 0, "credit": obligation.original_amount},
            ],
        )
        return AccrualDocument.objects.create(
            club=obligation.club, period=period, document_type=AccrualDocumentType.PAYABLE,
            counterparty_wallet=obligation.recipient_wallet,
            counterparty_label=obligation.description or "Payroll recipient",
            recognition_account=ChartOfAccountsService.account(obligation.club, expense_code),
            control_account=ChartOfAccountsService.account(obligation.club, GLCode.PAYROLL_PAYABLE),
            original_amount=obligation.original_amount, settled_amount=Decimal("0"),
            recognized_on=recognized_on, due_date=obligation.due_date, status=AccrualStatus.OPEN,
            source_type="PAYROLL_OBLIGATION", source_id=str(obligation.pk), recognition_journal=journal,
            idempotency_key=f"payroll-accrual:{obligation.pk}",
            metadata={"obligation_type": obligation.obligation_type},
        )

    @classmethod
    @transaction.atomic
    def ensure_debt_document(cls, installment, component):
        from club_debt.models import LoanInstallment
        installment = LoanInstallment.objects.select_for_update().select_related("agreement", "agreement__lender_wallet").get(pk=installment.pk)
        component = component.upper()
        if component not in {"INTEREST", "PENALTY"}:
            raise BudgetIntegrityError("Unsupported debt accrual component")
        amount = installment.interest_due if component == "INTEREST" else installment.penalty_due
        amount = q8(amount)
        if amount <= 0:
            return None
        club = installment.agreement.borrower_club
        source_type = f"LOAN_{component}"
        existing = AccrualDocument.objects.filter(
            club=club, document_type=AccrualDocumentType.PAYABLE, source_type=source_type, source_id=str(installment.pk)
        ).first()
        if existing:
            return existing
        period = JournalService._period_for(club, installment.due_date)
        if period is None or period.is_closed:
            return None
        expense_code = GLCode.DEBT_INTEREST if component == "INTEREST" else GLCode.DEBT_FEES
        journal = JournalService.post(
            club=club, period=period, accounting_date=installment.due_date, source_type="DEBT_ACCRUAL",
            source_id=f"{installment.pk}:{component}", idempotency_key=f"gl-debt-accrual:{installment.pk}:{component}",
            memo=f"Loan {component.lower()} accrual",
            lines=[
                {"account": expense_code, "debit": amount, "credit": 0},
                {"account": GLCode.ACCOUNTS_PAYABLE, "debit": 0, "credit": amount},
            ],
        )
        return AccrualDocument.objects.create(
            club=club, period=period, document_type=AccrualDocumentType.PAYABLE,
            counterparty_wallet=installment.agreement.lender_wallet,
            counterparty_label=f"Loan lender / installment {installment.sequence}",
            recognition_account=ChartOfAccountsService.account(club, expense_code),
            control_account=ChartOfAccountsService.account(club, GLCode.ACCOUNTS_PAYABLE),
            original_amount=amount, recognized_on=installment.due_date, due_date=installment.due_date,
            source_type=source_type, source_id=str(installment.pk), recognition_journal=journal,
            idempotency_key=f"debt-accrual:{installment.pk}:{component}",
            metadata={"agreement_id": str(installment.agreement_id), "component": component},
        )

    @classmethod
    def sync_debt(cls, *, club, through_date):
        from club_debt.models import LoanInstallment
        qs = LoanInstallment.objects.filter(agreement__borrower_club=club, due_date__lte=through_date).select_related(
            "agreement", "agreement__lender_wallet"
        )
        created = 0
        for inst in qs.iterator():
            for component, amount in (("INTEREST", inst.interest_due), ("PENALTY", inst.penalty_due)):
                if q8(amount) <= 0:
                    continue
                source_type = f"LOAN_{component}"
                if not AccrualDocument.objects.filter(club=club, source_type=source_type, source_id=str(inst.pk)).exists():
                    if cls.ensure_debt_document(inst, component):
                        created += 1
        return {"debt_accruals_created": created}

    @classmethod
    def sync_payroll(cls, *, club, through_date):
        from club_payroll.constants import ObligationStatus
        from club_payroll.models import PayrollObligation
        qs = PayrollObligation.objects.filter(club=club, due_date__lte=through_date).exclude(
            status__in=[ObligationStatus.CANCELLED, ObligationStatus.WAIVED]
        ).select_related("plan", "recipient_wallet")
        created = 0
        for obligation in qs.iterator():
            if not AccrualDocument.objects.filter(club=club, source_type="PAYROLL_OBLIGATION", source_id=str(obligation.pk)).exists():
                if cls.ensure_payroll_document(obligation):
                    created += 1
        return {"payroll_accruals_created": created}

    @classmethod
    @transaction.atomic
    def create_manual_document(cls, *, club, document_type, amount, recognized_on, due_date,
                               recognition_account_code, counterparty_wallet=None, counterparty_label="",
                               source_type="MANUAL_ACCRUAL", source_id="", idempotency_key, memo=""):
        amount = q8(amount)
        if amount <= 0:
            raise BudgetIntegrityError("Accrual amount must be positive")
        existing = AccrualDocument.objects.filter(idempotency_key=idempotency_key).first()
        if existing:
            if (existing.club_id,existing.document_type,existing.original_amount,existing.recognized_on,existing.due_date,existing.recognition_account.code)!=(club.pk,document_type,amount,recognized_on,due_date,recognition_account_code):
                raise BudgetIntegrityError('Accrual idempotency key belongs to different recognition terms')
            return existing
        source_id = str(source_id or idempotency_key)
        ChartOfAccountsService.ensure_defaults(club)
        period = JournalService._period_for(club, recognized_on)
        if period is None:
            raise BudgetIntegrityError("No accounting period covers accrual recognition date")
        if document_type == AccrualDocumentType.PAYABLE:
            lines = [
                {"account": recognition_account_code, "debit": amount, "credit": 0},
                {"account": GLCode.ACCOUNTS_PAYABLE, "debit": 0, "credit": amount},
            ]
            control_code = GLCode.ACCOUNTS_PAYABLE
        else:
            lines = [
                {"account": GLCode.ACCOUNTS_RECEIVABLE, "debit": amount, "credit": 0},
                {"account": recognition_account_code, "debit": 0, "credit": amount},
            ]
            control_code = GLCode.ACCOUNTS_RECEIVABLE
        journal = JournalService.post(
            club=club, period=period, accounting_date=recognized_on, source_type=source_type,
            source_id=source_id, lines=lines, idempotency_key=f"gl-accrual:{idempotency_key}", memo=memo,
        )
        return AccrualDocument.objects.create(
            club=club, period=period, document_type=document_type,
            counterparty_wallet=counterparty_wallet, counterparty_label=counterparty_label,
            recognition_account=ChartOfAccountsService.account(club, recognition_account_code),
            control_account=ChartOfAccountsService.account(club, control_code),
            original_amount=amount, recognized_on=recognized_on, due_date=due_date,
            source_type=source_type, source_id=str(source_id), recognition_journal=journal,
            idempotency_key=idempotency_key,
        )

    @classmethod
    @transaction.atomic
    def apply_settlement(cls, *, document, ledger_entry, journal_entry, amount):
        document = AccrualDocument.objects.select_for_update().get(pk=document.pk)
        amount = min(q8(amount), q8(document.outstanding_amount))
        if amount <= 0:
            return None
        settlement, created = AccrualSettlement.objects.get_or_create(
            document=document, ledger_entry=ledger_entry,
            defaults={"journal_entry": journal_entry, "amount": amount},
        )
        if not created:
            return settlement
        document.settled_amount = q8(document.settled_amount + amount)
        document.status = AccrualStatus.SETTLED if document.settled_amount >= document.original_amount else AccrualStatus.PARTIAL
        document.save(update_fields=["settled_amount", "status", "updated_at"])
        return settlement


class OpeningBalanceService:
    @classmethod
    @transaction.atomic
    def ensure_cash_opening(cls, *, club, period):
        if JournalEntry.objects.filter(club=club, source_type="OPENING_BALANCE").exists():
            return None
        # If the club already has earlier GL history, balances roll forward; no
        # synthetic opening entry is required for later periods.
        if JournalEntry.objects.filter(club=club, accounting_date__lt=period.starts_at.date()).exists():
            return None
        wallet = Wallet.objects.filter(club=club).first()
        if not wallet:
            return None
        first = LedgerEntry.objects.filter(
            Q(source_wallet=wallet) | Q(destination_wallet=wallet), created_at__gte=period.starts_at
        ).order_by("created_at", "id").first()
        if first:
            if first.source_wallet_id == wallet.id:
                opening_cash = first.source_balance_before or ZERO
            else:
                opening_cash = first.destination_balance_before or ZERO
        else:
            opening_cash = q8(wallet.available_balance + wallet.reserved_balance)
        opening_cash = q8(opening_cash)
        if opening_cash <= 0:
            return None
        return JournalService.post(
            club=club, period=period, accounting_date=period.starts_at.date(), source_type="OPENING_BALANCE",
            source_id=str(period.pk), idempotency_key=f"gl-opening-cash:{club.pk}:{period.pk}",
            memo="Opening club treasury balance",
            lines=[
                {"account": GLCode.CASH, "debit": opening_cash, "credit": 0},
                {"account": GLCode.OPENING_EQUITY, "debit": 0, "credit": opening_cash},
            ],
        )


class LedgerPostingService:
    INCOME_MAP = {
        "CLUB_MATCHDAY_REVENUE": GLCode.MATCHDAY_REVENUE,
        "MATCH_REWARD": GLCode.PRIZE_REVENUE,
        "LEAGUE_REWARD": GLCode.PRIZE_REVENUE,
        "CUP_REWARD": GLCode.PRIZE_REVENUE,
        "SEASON_REWARD": GLCode.PRIZE_REVENUE,
        "PERFORMANCE_REWARD": GLCode.PRIZE_REVENUE,
        "FEDERATION_REWARD": GLCode.PRIZE_REVENUE,
        "CLUB_COMMERCIAL_REVENUE": GLCode.COMMERCIAL_REVENUE,
        "SPONSORSHIP_REVENUE": GLCode.SPONSORSHIP_REVENUE,
        "TRANSFER_FEE": GLCode.TRANSFER_REVENUE,
        "PLAYER_LOAN_FEE": GLCode.TRANSFER_REVENUE,
    }
    EXPENSE_MAP = {
        "CONTRACT_SALARY": GLCode.PLAYER_WAGES,
        "CLUB_STAFF_SALARY": GLCode.STAFF_WAGES,
        "CLUB_PAYROLL_BONUS": GLCode.PAYROLL_BONUS,
        "CONTRACT_SIGNING_BONUS": GLCode.SIGNING_BONUS,
        "CONTRACT_TERMINATION_COMPENSATION": GLCode.TERMINATION_COMPENSATION,
        "PLAYER_LOAN_FEE": GLCode.PLAYER_LOAN_EXPENSE,
        "CLUB_COMMERCIAL_EXPENSE": GLCode.FACILITY_OPEX,
        "TRAINING": GLCode.TRAINING_OPEX,
        "NUTRITION": GLCode.NUTRITION_OPEX,
        "CONTRACT_FEDERATION_FEE": GLCode.FEDERATION_FEES,
        "LEAGUE_REGISTRATION_FEE": GLCode.FEDERATION_FEES,
        "CUP_REGISTRATION_FEE": GLCode.FEDERATION_FEES,
        "TOURNAMENT_REGISTRATION_FEE": GLCode.FEDERATION_FEES,
        "FEDERATION_FINE": GLCode.FINES,
        "CLUB_LOAN_INTEREST_PAYMENT": GLCode.DEBT_INTEREST,
        "CLUB_LOAN_PENALTY_PAYMENT": GLCode.DEBT_FEES,
        "CLUB_LOAN_FEE": GLCode.DEBT_FEES,
    }

    @classmethod
    def _payroll_document(cls, entry, club):
        if entry.reference_type != "PAYROLL_OBLIGATION" or not entry.reference_id:
            return None
        from club_payroll.models import PayrollObligation
        try:
            obligation = PayrollObligation.objects.select_related("plan", "recipient_wallet").get(pk=entry.reference_id, club=club)
        except (PayrollObligation.DoesNotExist, ValueError):
            return None
        return AccrualAccountingService.ensure_payroll_document(obligation)

    @classmethod
    def _debt_document(cls, entry, club):
        if entry.reference_type != "LOAN_INSTALLMENT" or not entry.reference_id:
            return None
        component = None
        if entry.transaction_type == "CLUB_LOAN_INTEREST_PAYMENT":
            component = "INTEREST"
        elif entry.transaction_type == "CLUB_LOAN_PENALTY_PAYMENT":
            component = "PENALTY"
        if not component:
            return None
        from club_debt.models import LoanInstallment
        try:
            inst = LoanInstallment.objects.select_related("agreement", "agreement__lender_wallet").get(
                pk=entry.reference_id, agreement__borrower_club=club
            )
        except (LoanInstallment.DoesNotExist, ValueError):
            return None
        return AccrualAccountingService.ensure_debt_document(inst, component)

    @classmethod
    @transaction.atomic
    def post_entry(cls, *, club, entry):
        existing = JournalEntry.objects.filter(club=club, economy_ledger=entry).first()
        if existing:
            return existing
        wallet = Wallet.objects.filter(club=club).first()
        if not wallet:
            return None
        incoming = entry.destination_wallet_id == wallet.id
        outgoing = entry.source_wallet_id == wallet.id
        if not incoming and not outgoing:
            return None
        accounting_date = timezone.localtime(entry.created_at).date() if timezone.is_aware(entry.created_at) else entry.created_at.date()
        period = JournalService._period_for(club, accounting_date)
        if period is None or period.is_closed:
            return None
        amount = q8(entry.amount)
        lines = []
        settlement_doc = None

        if outgoing:
            if entry.transaction_type == "FRIENDLY_RESERVE":
                offset = GLCode.OTHER_CURRENT_ASSET
            elif entry.transaction_type == "MARKETPLACE_ESCROW":
                if entry.reference_type == "MARKET_LEASE_RENT":
                    offset = GLCode.FACILITY_OPEX
                else:
                    offset = GLCode.MARKETPLACE_DEPOSIT
            elif entry.transaction_type == "TRANSFER_FEE":
                offset = GLCode.PLAYER_REGISTRATION_ASSET
            elif entry.transaction_type == "ITEM_PURCHASE":
                offset = GLCode.FACILITY_OPEX if entry.reference_type == "CLUB_ASSET_MAINTENANCE" else GLCode.CLUB_FACILITIES if entry.reference_type in {"CLUB_ASSET_UPGRADE","STARTER_STADIUM"} else GLCode.OTHER_NFT_ASSETS
            elif entry.transaction_type == "CLUB_LOAN_PRINCIPAL_REPAYMENT":
                offset = GLCode.LOANS_PAYABLE
            elif entry.transaction_type == "WITHDRAWAL":
                offset = GLCode.OWNER_DRAWS
            else:
                settlement_doc = cls._payroll_document(entry, club) or cls._debt_document(entry, club)
                offset = settlement_doc.control_account.code if settlement_doc else cls.EXPENSE_MAP.get(entry.transaction_type, GLCode.OTHER_EXPENSE)
            lines = [
                {"account": offset, "debit": amount, "credit": 0, "description": entry.description},
                {"account": GLCode.CASH, "debit": 0, "credit": amount, "description": entry.description},
            ]
        else:
            if entry.transaction_type == "FRIENDLY_REFUND":
                offset = GLCode.OTHER_CURRENT_ASSET
            elif entry.transaction_type == "MARKETPLACE_REFUND":
                offset = GLCode.MARKETPLACE_DEPOSIT
            elif entry.transaction_type == "CLUB_LOAN_DISBURSEMENT":
                offset = GLCode.LOANS_PAYABLE
            elif entry.transaction_type in {"DEPOSIT","ADMIN_ADJUSTMENT"}:
                offset = GLCode.OWNER_CAPITAL
            elif entry.transaction_type == "PLAYER_LOAN_WAGE_CONTRIBUTION":
                offset = GLCode.PLAYER_WAGES
            elif entry.transaction_type == "MARKETPLACE_SETTLEMENT":
                offset = GLCode.COMMERCIAL_REVENUE if entry.reference_type == "MARKET_LEASE" else GLCode.ASSET_SALE_PROCEEDS
            else:
                offset = cls.INCOME_MAP.get(entry.transaction_type, GLCode.OTHER_REVENUE)
            lines = [
                {"account": GLCode.CASH, "debit": amount, "credit": 0, "description": entry.description},
                {"account": offset, "debit": 0, "credit": amount, "description": entry.description},
            ]

        journal = JournalService.post(
            club=club, period=period, accounting_date=accounting_date,
            source_type="ECONOMY_LEDGER", source_id=str(entry.pk), economy_ledger=entry,
            lines=lines, idempotency_key=f"gl-ledger:{club.pk}:{entry.pk}", memo=entry.description,
        )
        if settlement_doc:
            AccrualAccountingService.apply_settlement(
                document=settlement_doc, ledger_entry=entry, journal_entry=journal, amount=amount
            )
        AssetAccountingService.after_cash_ledger_posted(club=club, entry=entry, journal=journal)
        return journal

    @classmethod
    def sync_club(cls, *, club, period=None):
        ChartOfAccountsService.ensure_defaults(club)
        wallet = Wallet.objects.filter(club=club).first()
        if not wallet:
            return {"posted": 0, "skipped": 0}
        qs = LedgerEntry.objects.filter(Q(source_wallet=wallet) | Q(destination_wallet=wallet)).order_by("created_at", "id")
        if period:
            qs = qs.filter(created_at__gte=period.starts_at, created_at__lt=period.ends_at)
        posted = skipped = 0
        for entry in qs.iterator():
            if JournalEntry.objects.filter(club=club, economy_ledger=entry).exists():
                continue
            try:
                if cls.post_entry(club=club, entry=entry):
                    posted += 1
                else:
                    skipped += 1
            except BudgetIntegrityError:
                skipped += 1
        return {"posted": posted, "skipped": skipped, "ledger_count": qs.count()}


class AssetAccountingService:
    @classmethod
    def after_cash_ledger_posted(cls, *, club, entry, journal):
        if entry.reference_type == 'STARTER_STADIUM' and entry.source_wallet_id:
            from clubs.models import ClubStadiumPurchase
            purchase=ClubStadiumPurchase.objects.filter(club=club,ledger_entry=entry).first()
            if purchase:
                FixedAssetBook.objects.get_or_create(club=club,asset=purchase.stadium,source_type='STARTER_STADIUM',source_id=str(purchase.pk),defaults={
                    'acquisition_cost':entry.amount,'residual_value':ZERO,'useful_life_months':240,'placed_in_service':entry.created_at.date()})
        if entry.transaction_type == "TRANSFER_FEE" and entry.reference_type.lower() == "transfer":
            cls._register_player_acquisition(club=club, entry=entry)
        elif entry.transaction_type == "ITEM_PURCHASE" and entry.reference_type == "CLUB_ASSET_UPGRADE" and entry.source_wallet_id:
            cls._capitalize_upgrade(club=club, entry=entry)

    @classmethod
    @transaction.atomic
    def _register_player_acquisition(cls, *, club, entry):
        if entry.reference_type.lower() != "transfer" or not entry.reference_id:
            return None
        from transfers.models import Transfer
        try:
            transfer = Transfer.objects.select_related("player", "destination_contract").get(pk=entry.reference_id, destination_club=club)
        except (Transfer.DoesNotExist, ValueError):
            return None
        contract = transfer.destination_contract
        if contract is None:
            return None
        obj, _ = PlayerRegistrationAsset.objects.get_or_create(
            contract=contract,
            defaults={
                "club": club, "player": transfer.player, "acquisition_cost": entry.amount,
                "starts_on": contract.start_date, "ends_on": contract.end_date,
                "source_transfer_id": transfer.pk,
            },
        )
        return obj

    @classmethod
    @transaction.atomic
    def _capitalize_upgrade(cls, *, club, entry):
        from club_assets.models import ClubAsset
        try:
            asset = ClubAsset.objects.get(pk=entry.reference_id, owner_club=club)
        except (ClubAsset.DoesNotExist, ValueError):
            return None
        book = FixedAssetBook.objects.filter(asset=asset, club=club, disposed_on__isnull=True).first()
        if book:
            book.acquisition_cost = q8(book.acquisition_cost + entry.amount)
            book.save(update_fields=["acquisition_cost", "updated_at"])
        else:
            life = 240 if asset.asset_type == "STADIUM" else 120
            book = FixedAssetBook.objects.create(
                club=club, asset=asset, acquisition_cost=entry.amount, residual_value=Decimal("0"),
                useful_life_months=life, placed_in_service=entry.created_at.date(),
                source_type="CLUB_ASSET_UPGRADE", source_id=str(asset.pk),
            )
        return book

    @classmethod
    def sync_marketplace_assets(cls, *, club, period=None):
        from asset_registry.models import AssetNamespace
        from marketplace.models import MarketplaceSale
        wallet = Wallet.objects.filter(club=club).first()
        if not wallet:
            return {"acquired": 0, "disposed": 0, "adjusted": 0}
        qs = MarketplaceSale.objects.filter(asset__namespace=AssetNamespace.CLUB_ASSET).select_related("asset")
        if period:
            qs = qs.filter(created_at__gte=period.starts_at, created_at__lt=period.ends_at)
        acquired = disposed = adjusted = 0
        for sale in qs.iterator():
            accounting_date = sale.created_at.date()
            target_period = JournalService._period_for(club, accounting_date)
            if not target_period or target_period.is_closed:
                continue
            source_asset = sale.asset.source_object_id
            from club_assets.models import ClubAsset
            try:
                asset = ClubAsset.objects.get(pk=source_asset)
            except (ClubAsset.DoesNotExist, ValueError):
                continue
            if sale.buyer_wallet_id == wallet.id:
                journal = JournalService.post(
                    club=club, period=target_period, accounting_date=accounting_date,
                    source_type="MARKETPLACE_ASSET_ACQUISITION", source_id=str(sale.pk),
                    idempotency_key=f"gl-market-acquire:{club.pk}:{sale.pk}", memo="Club facility acquisition",
                    lines=[
                        {"account": GLCode.CLUB_FACILITIES, "debit": sale.gross_amount, "credit": 0},
                        {"account": GLCode.MARKETPLACE_DEPOSIT, "debit": 0, "credit": sale.gross_amount},
                    ],
                )
                life = 240 if asset.asset_type == "STADIUM" else 120
                if not FixedAssetBook.objects.filter(asset=asset, club=club, disposed_on__isnull=True).exists():
                    FixedAssetBook.objects.create(
                        club=club, asset=asset, acquisition_cost=sale.gross_amount, residual_value=Decimal("0"),
                        useful_life_months=life, placed_in_service=accounting_date,
                        source_type="MARKETPLACE_SALE", source_id=str(sale.pk),
                    )
                    acquired += 1
            if sale.seller_wallet_id == wallet.id:
                book = FixedAssetBook.objects.filter(asset=asset, club=club, disposed_on__isnull=True).first()
                if book:
                    nbv = q8(book.carrying_amount)
                    lines = []
                    if book.accumulated_depreciation > 0:
                        lines.append({"account": GLCode.ACCUMULATED_DEPRECIATION, "debit": book.accumulated_depreciation, "credit": 0})
                    if nbv > 0:
                        lines.append({"account": GLCode.ASSET_DISPOSAL_COST, "debit": nbv, "credit": 0})
                    lines.append({"account": GLCode.CLUB_FACILITIES, "debit": 0, "credit": book.acquisition_cost})
                    JournalService.post(
                        club=club, period=target_period, accounting_date=accounting_date,
                        source_type="FIXED_ASSET_DISPOSAL", source_id=str(sale.pk), lines=lines,
                        idempotency_key=f"gl-fixed-dispose:{club.pk}:{sale.pk}", memo="Derecognize sold club facility",
                    )
                    book.disposed_on = accounting_date
                    book.save(update_fields=["disposed_on", "updated_at"])
                    disposed += 1
                fees = q8(sale.gross_amount - sale.seller_amount)
                if fees > 0:
                    JournalService.post(
                        club=club, period=target_period, accounting_date=accounting_date,
                        source_type="MARKETPLACE_SELLER_FEE_GROSSUP", source_id=str(sale.pk),
                        idempotency_key=f"gl-market-seller-fee:{club.pk}:{sale.pk}", memo="Marketplace selling fees",
                        lines=[
                            {"account": GLCode.MARKETPLACE_FEES, "debit": fees, "credit": 0},
                            {"account": GLCode.ASSET_SALE_PROCEEDS, "debit": 0, "credit": fees},
                        ],
                    )
                    adjusted += 1
        return {"acquired": acquired, "disposed": disposed, "adjusted": adjusted}

    @classmethod
    def sync_marketplace_leases(cls, *, club, period=None):
        from marketplace.models import MarketplaceLease
        wallet = Wallet.objects.filter(club=club).first()
        if not wallet:
            return {"lease_grossups": 0}
        qs = MarketplaceLease.objects.filter(owner_wallet=wallet).select_related("listing")
        if period:
            qs = qs.filter(created_at__gte=period.starts_at, created_at__lt=period.ends_at)
        count = 0
        for lease in qs.iterator():
            received = LedgerEntry.objects.filter(
                destination_wallet=wallet, transaction_type="MARKETPLACE_SETTLEMENT",
                reference_type="MARKET_LEASE", reference_id=str(lease.listing_id),
            ).aggregate(v=Sum("amount"))["v"] or ZERO
            fee = q8(lease.rent_amount - received)
            if fee <= 0:
                continue
            d = lease.created_at.date()
            p = JournalService._period_for(club, d)
            if not p or p.is_closed:
                continue
            JournalService.post(
                club=club, period=p, accounting_date=d, source_type="MARKETPLACE_LEASE_FEE_GROSSUP",
                source_id=str(lease.pk), idempotency_key=f"gl-lease-grossup:{club.pk}:{lease.pk}",
                memo="Marketplace lease fee gross-up",
                lines=[
                    {"account": GLCode.MARKETPLACE_FEES, "debit": fee, "credit": 0},
                    {"account": GLCode.COMMERCIAL_REVENUE, "debit": 0, "credit": fee},
                ],
            )
            count += 1
        return {"lease_grossups": count}

    @classmethod
    def sync_player_disposals(cls, *, club, period=None):
        from transfers.models import Transfer
        qs = Transfer.objects.filter(source_club=club, status="COMPLETED", completed_at__isnull=False).select_related("source_contract")
        if period:
            qs = qs.filter(completed_at__gte=period.starts_at, completed_at__lt=period.ends_at)
        count = 0
        for transfer in qs.iterator():
            if not transfer.source_contract_id:
                continue
            asset = PlayerRegistrationAsset.objects.filter(contract_id=transfer.source_contract_id, club=club, disposed_on__isnull=True).first()
            if not asset:
                continue
            d = transfer.completed_at.date()
            p = JournalService._period_for(club, d)
            if not p or p.is_closed:
                continue
            nbv = q8(asset.carrying_amount)
            if nbv > 0:
                JournalService.post(
                    club=club, period=p, accounting_date=d, source_type="PLAYER_REGISTRATION_DISPOSAL",
                    source_id=str(transfer.pk), idempotency_key=f"gl-player-disposal:{club.pk}:{transfer.pk}",
                    memo="Derecognize transferred player registration rights",
                    lines=[
                        {"account": GLCode.ASSET_DISPOSAL_COST, "debit": nbv, "credit": 0},
                        {"account": GLCode.PLAYER_REGISTRATION_ASSET, "debit": 0, "credit": nbv},
                    ],
                )
            asset.disposed_on = d
            asset.save(update_fields=["disposed_on", "updated_at"])
            count += 1
        return {"disposed_player_assets": count}

    @classmethod
    @transaction.atomic
    def run_depreciation(cls, *, club, through_date):
        posted = 0
        for book in FixedAssetBook.objects.select_for_update().filter(club=club, disposed_on__isnull=True).select_related("asset"):
            life_end = _add_months(book.placed_in_service, book.useful_life_months)
            end = min(through_date, life_end - timedelta(days=1))
            start = max(book.placed_in_service, (book.last_depreciated_through + timedelta(days=1)) if book.last_depreciated_through else book.placed_in_service)
            if end < start:
                continue
            total_days = max(1, (life_end - book.placed_in_service).days)
            days = (end - start).days + 1
            depreciable = max(ZERO, q8(book.acquisition_cost - book.residual_value))
            remaining = max(ZERO, q8(depreciable - book.accumulated_depreciation))
            amount = min(remaining, q8(depreciable * Decimal(days) / Decimal(total_days)))
            if amount <= 0:
                book.last_depreciated_through = end
                book.save(update_fields=["last_depreciated_through", "updated_at"])
                continue
            p = JournalService._period_for(club, end)
            if not p or p.is_closed:
                continue
            JournalService.post(
                club=club, period=p, accounting_date=end, source_type="FIXED_ASSET_DEPRECIATION", source_id=str(book.pk),
                idempotency_key=f"gl-fixed-depr:{book.pk}:{start}:{end}", memo=f"Depreciation: {book.asset.name}",
                lines=[
                    {"account": GLCode.DEPRECIATION_EXPENSE, "debit": amount, "credit": 0},
                    {"account": GLCode.ACCUMULATED_DEPRECIATION, "debit": 0, "credit": amount},
                ],
            )
            book.accumulated_depreciation = q8(book.accumulated_depreciation + amount)
            book.last_depreciated_through = end
            book.save(update_fields=["accumulated_depreciation", "last_depreciated_through", "updated_at"])
            posted += 1
        return {"fixed_asset_depreciation_entries": posted}

    @classmethod
    @transaction.atomic
    def run_player_amortization(cls, *, club, through_date):
        posted = 0
        for asset in PlayerRegistrationAsset.objects.select_for_update().filter(club=club, disposed_on__isnull=True):
            end = min(through_date, asset.ends_on - timedelta(days=1))
            start = max(asset.starts_on, (asset.last_amortized_through + timedelta(days=1)) if asset.last_amortized_through else asset.starts_on)
            if end < start:
                continue
            total_days = max(1, (asset.ends_on - asset.starts_on).days)
            days = (end - start).days + 1
            remaining = max(ZERO, q8(asset.acquisition_cost - asset.accumulated_amortization))
            amount = min(remaining, q8(asset.acquisition_cost * Decimal(days) / Decimal(total_days)))
            if amount <= 0:
                asset.last_amortized_through = end
                asset.save(update_fields=["last_amortized_through", "updated_at"])
                continue
            p = JournalService._period_for(club, end)
            if not p or p.is_closed:
                continue
            JournalService.post(
                club=club, period=p, accounting_date=end, source_type="PLAYER_REGISTRATION_AMORTIZATION", source_id=str(asset.pk),
                idempotency_key=f"gl-player-amort:{asset.pk}:{start}:{end}", memo="Player registration-right amortization",
                lines=[
                    {"account": GLCode.PLAYER_AMORTIZATION_EXPENSE, "debit": amount, "credit": 0},
                    {"account": GLCode.PLAYER_REGISTRATION_ASSET, "debit": 0, "credit": amount},
                ],
            )
            asset.accumulated_amortization = q8(asset.accumulated_amortization + amount)
            asset.last_amortized_through = end
            asset.save(update_fields=["accumulated_amortization", "last_amortized_through", "updated_at"])
            posted += 1
        return {"player_amortization_entries": posted}


class FinancialStatementService:
    @staticmethod
    def _account_rows(*, club, through_date=None, period=None, exclude_closing=False):
        qs = JournalLine.objects.filter(entry__club=club, entry__status__in=[JournalStatus.POSTED, JournalStatus.REVERSED]).select_related("account", "entry")
        if through_date:
            qs = qs.filter(entry__accounting_date__lte=through_date)
        if period:
            qs = qs.filter(entry__period=period)
        if exclude_closing:
            qs = qs.exclude(entry__source_type="PERIOD_CLOSE")
        rows = qs.values("account__id", "account__code", "account__name", "account__account_type", "account__normal_balance").annotate(
            debit=Sum("debit"), credit=Sum("credit")
        ).order_by("account__code")
        result = []
        for row in rows:
            debit = q8(row["debit"] or ZERO); credit = q8(row["credit"] or ZERO)
            normal = row["account__normal_balance"]
            balance = q8(debit - credit) if normal == GLNormalBalance.DEBIT else q8(credit - debit)
            result.append({**row, "debit": debit, "credit": credit, "balance": balance})
        return result

    @classmethod
    def trial_balance(cls, *, club, through_date=None, period=None):
        rows = cls._account_rows(club=club, through_date=through_date, period=period)
        td = q8(sum((r["debit"] for r in rows), ZERO)); tc = q8(sum((r["credit"] for r in rows), ZERO))
        return {
            "club_id": str(club.pk), "through_date": through_date.isoformat() if through_date else None,
            "period_id": str(period.pk) if period else None, "total_debit": str(td), "total_credit": str(tc),
            "balanced": td == tc,
            "accounts": [{**r, "debit": str(r["debit"]), "credit": str(r["credit"]), "balance": str(r["balance"])} for r in rows],
        }

    @classmethod
    def income_statement(cls, *, club, period):
        rows = cls._account_rows(club=club, period=period, exclude_closing=True)
        revenue = [r for r in rows if r["account__account_type"] == GLAccountType.REVENUE and r["balance"] != 0]
        expenses = [r for r in rows if r["account__account_type"] == GLAccountType.EXPENSE and r["balance"] != 0]
        total_revenue = q8(sum((r["balance"] for r in revenue), ZERO))
        total_expense = q8(sum((r["balance"] for r in expenses), ZERO))
        return {
            "statement": StatementType.INCOME_STATEMENT, "club_id": str(club.pk), "period_id": str(period.pk),
            "period_start": period.starts_at.date().isoformat(), "period_end": period.ends_at.date().isoformat(),
            "revenue": [{"code": r["account__code"], "name": r["account__name"], "amount": str(r["balance"])} for r in revenue],
            "expenses": [{"code": r["account__code"], "name": r["account__name"], "amount": str(r["balance"])} for r in expenses],
            "total_revenue": str(total_revenue), "total_expense": str(total_expense), "net_income": str(q8(total_revenue-total_expense)),
        }

    @classmethod
    def balance_sheet(cls, *, club, as_of):
        rows = cls._account_rows(club=club, through_date=as_of)
        assets = [r for r in rows if r["account__account_type"] == GLAccountType.ASSET and r["balance"] != 0]
        liabilities = [r for r in rows if r["account__account_type"] == GLAccountType.LIABILITY and r["balance"] != 0]
        equity = [r for r in rows if r["account__account_type"] == GLAccountType.EQUITY and r["balance"] != 0]
        revenues = [r for r in rows if r["account__account_type"] == GLAccountType.REVENUE]
        expenses = [r for r in rows if r["account__account_type"] == GLAccountType.EXPENSE]
        current_earnings = q8(sum((r["balance"] for r in revenues), ZERO) - sum((r["balance"] for r in expenses), ZERO))
        def signed_balance(r):
            amount = r["balance"]
            if r["account__account_type"] == GLAccountType.ASSET:
                return amount if r["account__normal_balance"] == GLNormalBalance.DEBIT else -amount
            if r["account__account_type"] in [GLAccountType.LIABILITY, GLAccountType.EQUITY]:
                return amount if r["account__normal_balance"] == GLNormalBalance.CREDIT else -amount
            return amount
        total_assets = q8(sum((signed_balance(r) for r in assets), ZERO))
        total_liabilities = q8(sum((signed_balance(r) for r in liabilities), ZERO))
        total_equity = q8(sum((signed_balance(r) for r in equity), ZERO))
        rhs = q8(total_liabilities + total_equity + current_earnings)
        def serialize(items):
            return [{"code": r["account__code"], "name": r["account__name"], "amount": str(q8(signed_balance(r)))} for r in items]
        return {
            "statement": StatementType.BALANCE_SHEET, "club_id": str(club.pk), "as_of": as_of.isoformat(),
            "assets": serialize(assets), "liabilities": serialize(liabilities), "equity": serialize(equity),
            "current_unclosed_earnings": str(current_earnings),
            "total_assets": str(total_assets), "total_liabilities": str(total_liabilities),
            "total_equity_excluding_current_earnings": str(total_equity), "liabilities_and_equity": str(rhs),
            "balanced": total_assets == rhs,
        }

    @classmethod
    def cash_flow(cls, *, club, period):
        ChartOfAccountsService.ensure_defaults(club)
        cash = ChartOfAccountsService.account(club, GLCode.CASH)
        entries = JournalEntry.objects.filter(club=club, period=period).exclude(source_type="PERIOD_CLOSE").prefetch_related("lines__account")
        operating = investing = financing = ZERO
        details = []
        for entry in entries:
            cash_lines = [x for x in entry.lines.all() if x.account_id == cash.id]
            if not cash_lines:
                continue
            cash_change = q8(sum((x.debit - x.credit for x in cash_lines), ZERO))
            if cash_change == 0:
                continue
            other_codes = {x.account.code for x in entry.lines.all() if x.account_id != cash.id}
            if other_codes & {GLCode.LOANS_PAYABLE, GLCode.OWNER_CAPITAL, GLCode.OWNER_DRAWS}:
                bucket = "FINANCING"; financing += cash_change
            elif other_codes & {GLCode.PLAYER_REGISTRATION_ASSET, GLCode.CLUB_FACILITIES, GLCode.OTHER_NFT_ASSETS, GLCode.MARKETPLACE_DEPOSIT}:
                bucket = "INVESTING"; investing += cash_change
            else:
                bucket = "OPERATING"; operating += cash_change
            details.append({"journal_no": entry.journal_no, "date": entry.accounting_date.isoformat(), "bucket": bucket, "amount": str(cash_change), "source_type": entry.source_type})
        net = q8(operating + investing + financing)
        return {
            "statement": StatementType.CASH_FLOW, "club_id": str(club.pk), "period_id": str(period.pk),
            "operating_cash_flow": str(q8(operating)), "investing_cash_flow": str(q8(investing)),
            "financing_cash_flow": str(q8(financing)), "net_change_in_cash": str(net), "details": details,
        }

    @classmethod
    def three_statements(cls, *, club, period):
        return {
            "income_statement": cls.income_statement(club=club, period=period),
            "balance_sheet": cls.balance_sheet(club=club, as_of=(period.ends_at - timedelta(microseconds=1)).date()),
            "cash_flow": cls.cash_flow(club=club, period=period),
        }

    @classmethod
    @transaction.atomic
    def snapshot_period(cls, *, period):
        club = period.club
        payloads = [
            (StatementType.INCOME_STATEMENT, cls.income_statement(club=club, period=period)),
            (StatementType.BALANCE_SHEET, cls.balance_sheet(club=club, as_of=(period.ends_at - timedelta(microseconds=1)).date())),
            (StatementType.CASH_FLOW, cls.cash_flow(club=club, period=period)),
            (StatementType.TRIAL_BALANCE, cls.trial_balance(club=club, period=period)),
        ]
        snapshots = []
        for statement_type, payload in payloads:
            snapshot, _ = FinancialStatementSnapshot.objects.update_or_create(
                period=period, statement_type=statement_type,
                defaults={"club": club, "as_of": (period.ends_at - timedelta(microseconds=1)).date(), "payload": payload, "checksum": _hash(payload)},
            )
            snapshots.append(snapshot)
        return snapshots


class ReconciliationService:
    @classmethod
    def status(cls, *, club, period=None):
        ChartOfAccountsService.ensure_defaults(club)
        wallet = Wallet.objects.filter(club=club).first()
        cash_account = ChartOfAccountsService.account(club, GLCode.CASH)
        cash_qs = JournalLine.objects.filter(entry__club=club, account=cash_account)
        if period:
            cash_qs = cash_qs.filter(entry__accounting_date__lt=period.ends_at.date())
        agg = cash_qs.aggregate(debit=Sum("debit"), credit=Sum("credit"))
        gl_cash = q8((agg["debit"] or ZERO) - (agg["credit"] or ZERO))
        unposted_qs = LedgerEntry.objects.none()
        wallet_total = None
        difference = None
        if wallet:
            ledger_qs = LedgerEntry.objects.filter(Q(source_wallet=wallet) | Q(destination_wallet=wallet))
            if period:
                ledger_qs = ledger_qs.filter(created_at__gte=period.starts_at, created_at__lt=period.ends_at)
            posted_ids = JournalEntry.objects.filter(club=club, economy_ledger__isnull=False).values_list("economy_ledger_id", flat=True)
            unposted_qs = ledger_qs.exclude(pk__in=posted_ids)
            if period is None:
                wallet_total = q8(wallet.available_balance + wallet.reserved_balance)
                difference = q8(gl_cash - wallet_total)
        trial = FinancialStatementService.trial_balance(club=club, period=period)
        return {
            "club_id": str(club.pk), "period_id": str(period.pk) if period else None,
            "trial_balance_balanced": trial["balanced"], "gl_cash": str(gl_cash),
            "wallet_total_current": str(wallet_total) if wallet_total is not None else None,
            "current_cash_difference": str(difference) if difference is not None else None,
            "unposted_economy_ledger_entries": unposted_qs.count(),
            "reconciled_current_cash": (difference == 0) if difference is not None else None,
        }


class PeriodCloseService:
    @classmethod
    @transaction.atomic
    def close(cls, period):
        period = AccountingPeriod.objects.select_for_update().select_related("club").get(pk=period.pk)
        if period.is_closed:
            return period
        club = period.club
        end_date = (period.ends_at - timedelta(microseconds=1)).date()
        GeneralLedgerService.sync(club=club, period=period, through_date=end_date)
        trial = FinancialStatementService.trial_balance(club=club, period=period)
        if not trial["balanced"]:
            raise BudgetIntegrityError("Cannot close an unbalanced accounting period")
        FinancialStatementService.snapshot_period(period=period)
        rows = FinancialStatementService._account_rows(club=club, period=period, exclude_closing=True)
        lines = []
        retained_debit = ZERO
        retained_credit = ZERO
        for row in rows:
            code = row["account__code"]
            bal = q8(row["balance"])
            if bal == 0:
                continue
            if row["account__account_type"] == GLAccountType.REVENUE:
                if bal > 0:
                    lines.append({"account": code, "debit": bal, "credit": 0})
                    retained_credit += bal
                else:
                    lines.append({"account": code, "debit": 0, "credit": -bal})
                    retained_debit += -bal
            elif row["account__account_type"] == GLAccountType.EXPENSE:
                if bal > 0:
                    lines.append({"account": code, "debit": 0, "credit": bal})
                    retained_debit += bal
                else:
                    lines.append({"account": code, "debit": -bal, "credit": 0})
                    retained_credit += -bal
        net_retained = q8(retained_credit - retained_debit)
        if lines and net_retained != 0:
            if net_retained > 0:
                lines.append({"account": GLCode.RETAINED_EARNINGS, "debit": 0, "credit": net_retained})
            else:
                lines.append({"account": GLCode.RETAINED_EARNINGS, "debit": -net_retained, "credit": 0})
        if lines:
            JournalService.post(
                club=club, period=period, accounting_date=end_date, source_type="PERIOD_CLOSE", source_id=str(period.pk),
                idempotency_key=f"gl-period-close:{period.pk}", memo=f"Close accounting period {period.name}", lines=lines,
            )
        period.is_closed = True
        period.closed_at = timezone.now()
        period.save(update_fields=["is_closed", "closed_at"])
        FinancialControlEvent.objects.create(
            club=club, event_type="GENERAL_LEDGER_PERIOD_CLOSED", reference_type="ACCOUNTING_PERIOD",
            reference_id=str(period.pk), payload={"trial_balance_checksum": _hash(trial)},
        )
        return period


class GeneralLedgerService:
    @classmethod
    def sync(cls, *, club, period=None, through_date=None):
        ChartOfAccountsService.ensure_defaults(club)
        period = period or (AccountingPeriod.objects.filter(club=club, is_closed=False).order_by("starts_at").first())
        through_date = through_date or timezone.localdate()
        if period:
            OpeningBalanceService.ensure_cash_opening(club=club, period=period)
        ledger = LedgerPostingService.sync_club(club=club, period=period)
        payroll = AccrualAccountingService.sync_payroll(club=club, through_date=through_date)
        debt = AccrualAccountingService.sync_debt(club=club, through_date=through_date)
        market = AssetAccountingService.sync_marketplace_assets(club=club, period=period)
        leases = AssetAccountingService.sync_marketplace_leases(club=club, period=period)
        player_disposals = AssetAccountingService.sync_player_disposals(club=club, period=period)
        depreciation = AssetAccountingService.run_depreciation(club=club, through_date=through_date)
        amortization = AssetAccountingService.run_player_amortization(club=club, through_date=through_date)
        return {**ledger, **payroll, **debt, **market, **leases, **player_disposals, **depreciation, **amortization}
