"""
Django management command to setup accounting system.
Usage: python manage.py setup_accounting

Chart of Accounts is structured to satisfy an economic analyst / external auditor
reviewing a licensed Digital Credit Provider under CBK Prudential Guidelines.
Accounts align with the Income Statement and Statement of Financial Position
formats used by Haven Grazuri Credit Solutions Ltd (IFRS for SMEs).
"""

from django.core.management.base import BaseCommand
from django.db import transaction
from datetime import datetime, timedelta
from decimal import Decimal

from accounting.models import Account, FiscalPeriod
from users.models import CustomUser


class Command(BaseCommand):
    help = 'Setup Chart of Accounts and Fiscal Periods for Haven Grazuri Accounting System'

    def add_arguments(self, parser):
        parser.add_argument(
            '--update-names',
            action='store_true',
            help='Update names/descriptions of existing accounts (safe to re-run)',
        )

    def handle(self, *args, **options):
        self.update_names = options.get('update_names', False)
        self.stdout.write("\n" + "=" * 70)
        self.stdout.write("  Haven Grazuri Credit Solutions Ltd — Accounting System Setup")
        self.stdout.write("=" * 70 + "\n")

        try:
            with transaction.atomic():
                self.create_chart_of_accounts()
                self.create_fiscal_periods()
                self.print_summary()
            self.stdout.write(self.style.SUCCESS('\n✓ Setup completed successfully!\n'))
        except Exception as e:
            self.stdout.write(self.style.ERROR(f'\n✗ Setup failed: {str(e)}\n'))
            raise

    # ------------------------------------------------------------------
    # Chart of Accounts
    # ------------------------------------------------------------------

    def create_chart_of_accounts(self):
        self.stdout.write("\n" + "=" * 70)
        self.stdout.write("  Creating Chart of Accounts")
        self.stdout.write("=" * 70 + "\n")

        system_user = CustomUser.objects.filter(role='admin').first()

        # ── Account definitions ───────────────────────────────────────
        # Format: (code, name, type, subtype, description, is_system)
        # GL code numbering mirrors the Trial Balance report structure:
        #   1010–1xxx  Current Assets
        #   1500–1xxx  Non-Current Assets
        #   2010–2xxx  Current Liabilities
        #   2500–2xxx  Non-Current Liabilities
        #   3010–3xxx  Equity
        #   4xxx       Income
        #   5xxx       Expenses
        # ─────────────────────────────────────────────────────────────

        accounts_data = [

            # ══ CURRENT ASSETS ════════════════════════════════════════
            ('1010', 'Cash and Bank Balances',
             'asset', 'current_asset',
             'Cash on hand plus all bank and mobile-money balances (M-Pesa, SasaPay).', True),

            ('1011', 'Cash on Hand',
             'asset', 'current_asset',
             'Physical petty cash held at branch offices.', True),

            ('1012', 'Bank Account – Main Operating',
             'asset', 'current_asset',
             'Primary commercial bank current account used for disbursements and collections.', True),

            ('1013', 'M-Pesa / SasaPay Float',
             'asset', 'current_asset',
             'Mobile money float held in the SasaPay merchant wallet.', True),

            ('1020', 'Loan Portfolio – Performing',
             'asset', 'loan_portfolio',
             'Principal outstanding on loans that are current (0–30 days past due). '
             'Per IFRS 9 Stage 1.', True),

            ('1021', 'Loan Portfolio – Watch (Stage 2)',
             'asset', 'loan_portfolio',
             'Principal outstanding on loans 31–90 days past due. IFRS 9 Stage 2 '
             '(Significant Increase in Credit Risk).', True),

            ('1030', 'Loan Portfolio – Non-Performing',
             'asset', 'loan_portfolio',
             'Principal outstanding on loans 90+ days past due. IFRS 9 Stage 3 '
             '(Credit-Impaired). Reported separately per CBK guidelines.', True),

            ('1031', 'Allowance for Loan Losses (ECL)',
             'asset', 'loan_portfolio',
             'Expected Credit Loss reserve contra-asset calculated under IFRS 9. '
             'Reduces the gross loan portfolio to net carrying amount.', True),

            ('1040', 'Interest Receivable',
             'asset', 'current_asset',
             'Accrued interest income on performing loans not yet collected.', True),

            ('1050', 'Fees and Charges Receivable',
             'asset', 'current_asset',
             'Processing fees, registration fees, and penalty charges billed but unpaid.', True),

            ('1060', 'Prepayments and Advances',
             'asset', 'current_asset',
             'Rent prepayments, staff salary advances, and other prepaid expenses.', False),

            ('1070', 'Other Current Assets',
             'asset', 'current_asset',
             'Sundry receivables and short-term assets not classified elsewhere.', False),

            # ══ NON-CURRENT ASSETS ════════════════════════════════════
            ('1510', 'Property, Plant and Equipment (Gross)',
             'asset', 'fixed_asset',
             'Cost of computers, furniture, motor vehicles, and office fittings.', False),

            ('1511', 'Accumulated Depreciation – PPE',
             'asset', 'fixed_asset',
             'Contra-asset: accumulated depreciation charged against PPE. '
             'Net book value = 1510 − 1511.', False),

            ('1520', 'Intangible Assets (Gross)',
             'asset', 'fixed_asset',
             'Cost of software licences, core-banking system, and internally developed software.', False),

            ('1521', 'Accumulated Amortisation – Intangibles',
             'asset', 'fixed_asset',
             'Contra-asset: accumulated amortisation on intangible assets.', False),

            ('1530', 'Right-of-Use Assets',
             'asset', 'fixed_asset',
             'Present value of operating lease right-of-use assets recognised per IFRS 16.', False),

            ('1540', 'Deferred Tax Asset',
             'asset', 'other_asset',
             'Tax recoverable arising from deductible temporary differences (IAS 12).', False),

            ('1550', 'Other Non-Current Assets',
             'asset', 'other_asset',
             'Long-term security deposits, refundable deposits, and other non-current assets.', False),

            # ══ CURRENT LIABILITIES ═══════════════════════════════════
            ('2010', 'Borrowings – Current Portion',
             'liability', 'borrowings',
             'Instalments of bank loans and credit lines falling due within 12 months.', True),

            ('2020', 'Interest Payable',
             'liability', 'current_liability',
             'Interest accrued and payable on borrowings.', True),

            ('2030', 'Payables and Accruals',
             'liability', 'current_liability',
             'Trade creditors, accrued expenses (rent, utilities, professional fees).', True),

            ('2040', 'Income Tax Payable',
             'liability', 'current_liability',
             'Corporate income tax assessed and payable to the Kenya Revenue Authority.', True),

            ('2050', 'Statutory Deductions Payable',
             'liability', 'current_liability',
             'PAYE, NSSF, NHIF, and other statutory deductions remittable to authorities.', True),

            ('2060', 'Lease Liability – Current Portion',
             'liability', 'current_liability',
             'Current portion of IFRS 16 lease liabilities payable within 12 months.', False),

            ('2070', 'Client Savings Deposits',
             'liability', 'client_savings',
             'Savings and group deposits held on behalf of microfinance clients.', True),

            ('2080', 'Other Current Liabilities',
             'liability', 'current_liability',
             'Sundry payables and other short-term obligations.', False),

            # ══ NON-CURRENT LIABILITIES ═══════════════════════════════
            ('2510', 'Borrowings – Non-Current',
             'liability', 'borrowings',
             'Long-term debt: bank loans, development finance institution facilities '
             'with maturity beyond 12 months.', True),

            ('2520', 'Lease Liability – Non-Current',
             'liability', 'other_liability',
             'Non-current portion of IFRS 16 operating lease liabilities.', False),

            ('2530', 'Deferred Tax Liability',
             'liability', 'other_liability',
             'Deferred tax arising from taxable temporary differences (IAS 12).', False),

            ('2540', 'Other Non-Current Liabilities',
             'liability', 'other_liability',
             'Long-term security deposits received and other non-current obligations.', False),

            # ══ EQUITY ════════════════════════════════════════════════
            ('3010', 'Share Capital',
             'equity', None,
             'Paid-up ordinary share capital of Haven Grazuri Credit Solutions Ltd.', True),

            ('3020', 'Retained Earnings',
             'equity', None,
             'Accumulated net profits from prior years retained in the business.', True),

            ('3030', 'Current Year Surplus / (Deficit)',
             'equity', None,
             'Net profit or loss for the current financial year before appropriation.', True),

            ('3040', 'Other Comprehensive Income Reserve',
             'equity', None,
             'Cumulative OCI items: remeasurements of defined benefit plans, '
             'fair-value movements on FVOCI instruments.', False),

            # ══ INCOME ════════════════════════════════════════════════
            # Revenue – Note 1
            ('4010', 'Interest Income – Loans and Advances',
             'income', 'interest_income',
             'Interest charged on all loan products (flat-rate and reducing-balance). '
             'Mapped to Note 1 on the Income Statement.', True),

            # Note 2
            ('4020', 'Fee Income – Processing Fees',
             'income', 'fee_income',
             'Loan origination / processing fee charged at disbursement. Note 2.', True),

            # Note 2 (grouped with processing)
            ('4021', 'Fee Income – Registration Fees',
             'income', 'fee_income',
             'One-time client registration / membership fee. Note 2.', True),

            # Note 2 (grouped)
            ('4022', 'Fee Income – Late Payment Penalties',
             'income', 'fee_income',
             'Penalty interest charged on overdue instalments. Note 2.', True),

            # Note 3
            ('4030', 'Other Operating Income',
             'income', 'other_income',
             'Insurance commissions, training fees, consultancy income, and '
             'other non-core revenue. Note 3.', False),

            # ══ EXPENSES ══════════════════════════════════════════════
            # Note 4 – Interest Expense
            ('5010', 'Interest Expense – Borrowings',
             'expense', 'interest_expense',
             'Interest paid or accrued on bank loans and DFI credit lines. Note 4.', True),

            # Note 5 – Loan Loss Provision
            ('5020', 'Loan Loss Provision (ECL Charge)',
             'expense', 'loan_loss_provision',
             'Expected Credit Loss impairment charge per IFRS 9. Note 5.', True),

            ('5021', 'Loans Written Off',
             'expense', 'loan_loss_provision',
             'Principal balance of unrecoverable loans removed from the portfolio. Note 5.', True),

            ('5022', 'Bad Debt Recoveries',
             'expense', 'loan_loss_provision',
             'Cash recovered on previously written-off loans (credit/reversal). Note 5.', True),

            # Note 6 – Staff Costs
            ('5030', 'Salaries and Wages',
             'expense', 'staff_costs',
             'Gross salaries for all permanent and contract staff. Note 6.', True),

            ('5031', 'Pension and NSSF Contributions',
             'expense', 'staff_costs',
             "Employer's NSSF and occupational pension contributions. Note 6.", True),

            ('5032', 'NHIF and Medical Cover',
             'expense', 'staff_costs',
             "Employer's NHIF and private medical insurance. Note 6.", True),

            ('5033', 'Staff Training and Development',
             'expense', 'staff_costs',
             'Training, workshops, and professional development costs. Note 6.', False),

            # Note 7 – Administrative Expenses
            ('5040', 'Rent Expense',
             'expense', 'administrative_expense',
             'Short-term lease and office premises rental. Note 7.', False),

            ('5041', 'Utilities Expense',
             'expense', 'administrative_expense',
             'Electricity, water, and internet bills. Note 7.', False),

            ('5042', 'Office Supplies and Stationery',
             'expense', 'administrative_expense',
             'Consumable office materials. Note 7.', False),

            ('5043', 'Marketing and Advertising',
             'expense', 'administrative_expense',
             'Digital marketing, print media, and promotional activities. Note 7.', False),

            ('5044', 'Professional and Legal Fees',
             'expense', 'administrative_expense',
             'Legal counsel, external audit, and consultancy fees. Note 7.', False),

            ('5045', 'Bank Charges and Commissions',
             'expense', 'administrative_expense',
             'Bank transaction charges, M-Pesa and SasaPay API fees. Note 7.', True),

            ('5046', 'Insurance Premiums',
             'expense', 'administrative_expense',
             'Credit life insurance, fire and burglary, and fidelity cover. Note 7.', False),

            ('5047', 'Travel and Transport',
             'expense', 'administrative_expense',
             'Fuel, mileage, and public transport for business travel. Note 7.', False),

            ('5048', 'Communication and IT Expenses',
             'expense', 'administrative_expense',
             'Mobile airtime, data, software subscriptions, and IT support. Note 7.', False),

            # Note 8 – Depreciation and Amortisation
            ('5050', 'Depreciation – Property, Plant and Equipment',
             'expense', 'depreciation',
             'Depreciation of computers, furniture, and office fittings. Note 8.', False),

            ('5051', 'Amortisation – Intangible Assets',
             'expense', 'depreciation',
             'Amortisation of software and core-banking system licence. Note 8.', False),

            ('5052', 'Depreciation – Right-of-Use Assets',
             'expense', 'depreciation',
             'Depreciation on IFRS 16 right-of-use assets. Note 8.', False),

            # Note 9 – Other Operating Expenses
            ('5060', 'Regulatory and Compliance Fees',
             'expense', 'other_expense',
             'CBK annual licence fees and regulatory compliance costs. Note 9.', True),

            ('5061', 'Security and Guarding',
             'expense', 'other_expense',
             'Physical security services at branches. Note 9.', False),

            ('5062', 'Miscellaneous Operating Expenses',
             'expense', 'other_expense',
             'Other operating costs not classified above. Note 9.', False),

            # Note 10 – Taxation
            ('5070', 'Income Tax Expense – Current',
             'expense', 'taxation',
             'Corporate tax on current-year taxable income at the prevailing rate. Note 10.', True),

            ('5071', 'Deferred Tax Expense / (Credit)',
             'expense', 'taxation',
             'Movement in deferred tax balances arising from temporary differences. Note 10.', True),

        ]  # end accounts_data

        created_count = 0
        updated_count = 0
        existing_count = 0

        for entry in accounts_data:
            code, name, acc_type, subtype, description, is_system = entry
            defaults = {
                'name': name,
                'account_type': acc_type,
                'subtype': subtype,
                'description': description,
                'is_system_account': is_system,
                'is_active': True,
                'created_by': system_user,
            }
            account, created = Account.objects.get_or_create(
                code=code, defaults=defaults
            )
            if created:
                created_count += 1
                self.stdout.write(
                    self.style.SUCCESS(f'  [+] {code:8s}  {name}')
                )
            elif self.update_names:
                Account.objects.filter(code=code).update(
                    name=name, description=description,
                    account_type=acc_type, subtype=subtype,
                )
                updated_count += 1
                self.stdout.write(f'  [U] {code:8s}  {name}')
            else:
                existing_count += 1

        self.stdout.write(
            f'\n  Accounts: {created_count} created, '
            f'{updated_count} updated, {existing_count} already existed'
        )

    # ------------------------------------------------------------------
    # Fiscal Periods
    # ------------------------------------------------------------------

    def create_fiscal_periods(self):
        self.stdout.write("\n" + "=" * 70)
        self.stdout.write("  Creating Fiscal Periods")
        self.stdout.write("=" * 70 + "\n")

        year = datetime.now().year
        created_count = 0
        existing_count = 0

        # Monthly periods – current year and next year (for forward planning)
        for y in [year - 1, year, year + 1]:
            for month in range(1, 13):
                start_date = datetime(y, month, 1).date()
                if month == 12:
                    end_date = datetime(y, 12, 31).date()
                else:
                    end_date = (datetime(y, month + 1, 1) - timedelta(days=1)).date()

                period_name = start_date.strftime('%B %Y')
                # Close past periods automatically
                auto_status = 'open' if (y, month) >= (year - 1, datetime.now().month) else 'closed'

                period, created = FiscalPeriod.objects.get_or_create(
                    name=period_name,
                    period_type='monthly',
                    defaults={
                        'start_date': start_date,
                        'end_date': end_date,
                        'status': auto_status,
                    }
                )
                if created:
                    created_count += 1
                    self.stdout.write(
                        self.style.SUCCESS(f'  [+] {period.name}')
                    )
                else:
                    existing_count += 1

        # Annual periods
        for y in [year - 1, year, year + 1]:
            fy_name = f'FY {y}'
            period, created = FiscalPeriod.objects.get_or_create(
                name=fy_name,
                period_type='annual',
                defaults={
                    'start_date': datetime(y, 1, 1).date(),
                    'end_date': datetime(y, 12, 31).date(),
                    'status': 'open' if y >= year else 'closed',
                }
            )
            if created:
                created_count += 1
                self.stdout.write(self.style.SUCCESS(f'  [+] {period.name}'))
            else:
                existing_count += 1

        self.stdout.write(
            f'\n  Periods: {created_count} created, {existing_count} already existed'
        )

    # ------------------------------------------------------------------
    # Summary
    # ------------------------------------------------------------------

    def print_summary(self):
        self.stdout.write("\n" + "=" * 70)
        self.stdout.write("  Setup Complete")
        self.stdout.write("=" * 70)

        from django.db.models import Count
        type_counts = (
            Account.objects
            .filter(is_active=True)
            .values('account_type')
            .annotate(n=Count('id'))
            .order_by('account_type')
        )
        total = Account.objects.filter(is_active=True).count()

        self.stdout.write(f'\n  Active accounts: {total}')
        for row in type_counts:
            self.stdout.write(
                f"    {row['account_type'].upper():12s}: {row['n']} accounts"
            )

        self.stdout.write(f'\n  Fiscal periods: {FiscalPeriod.objects.count()}')
        self.stdout.write('\n  Quick links:')
        self.stdout.write('    Chart of Accounts : /accounting/accounts/')
        self.stdout.write('    Trial Balance     : /reports/financial/trial-balance/')
        self.stdout.write('    Income Statement  : /reports/financial/income-statement/')
        self.stdout.write('    Balance Sheet     : /reports/financial/balance-sheet/')
        self.stdout.write('    Journal Entries   : /accounting/journal/')
        self.stdout.write('    Reports Dashboard : /accounting/reports/dashboard/\n')
