"""
activate_accounting.py
======================
Activate the accounting module on production.
Runs fully automatically — no prompts.

Run on the server:
    cd /home/xygbfpsg/phingrazuri
    python activate_accounting.py
"""
import os
import sys
import subprocess

# ── Force correct DB credentials and settings ──────────────────────────────
os.environ['DJANGO_SETTINGS_MODULE'] = 'branch_system.settings_production'
os.environ['DB_NAME']     = 'xygbfpsg_loans'
os.environ['DB_USER']     = 'xygbfpsg_graz'
os.environ['DB_PASSWORD'] = 'j.ez-xy6##y.rllB'
os.environ['DB_HOST']     = 'localhost'
os.environ['DB_PORT']     = '3306'

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
MANAGE   = os.path.join(BASE_DIR, 'manage.py')
PYTHON   = sys.executable
ENV      = {**os.environ}


def run(cmd):
    label = ' '.join(os.path.basename(c) if i > 0 else c for i, c in enumerate(cmd))
    print("\n> " + label)
    rc = subprocess.call(cmd, env=ENV)
    return rc


def main():
    print("\n" + "=" * 70)
    print("  Haven Grazuri -- Accounting Module Activation")
    print("=" * 70)

    # 1. Migrations
    print("\n[1/4] Running migrations...")
    rc = run([PYTHON, MANAGE, 'migrate', '--run-syncdb'])
    if rc != 0:
        print("ERROR: migrations failed.")
        sys.exit(1)

    # 2. Chart of Accounts + Fiscal Periods
    print("\n[2/4] Setting up Chart of Accounts and Fiscal Periods...")
    rc = run([PYTHON, MANAGE, 'setup_accounting'])
    if rc != 0:
        print("ERROR: setup_accounting failed.")
        sys.exit(1)

    # 3. Real backfill (no prompt — dry run already confirmed in previous run)
    print("\n[3/4] Running GL backfill...")
    rc = run([PYTHON, MANAGE, 'backfill_gl_from_loans'])
    if rc != 0:
        print("WARNING: backfill completed with errors (see above).")
    else:
        print("Backfill completed successfully.")

    # 4. Health check
    print("\n[4/4] Health check...")
    health = (
        "import os, sys\n"
        "os.environ['DJANGO_SETTINGS_MODULE'] = 'branch_system.settings_production'\n"
        "os.environ['DB_NAME']     = 'xygbfpsg_loans'\n"
        "os.environ['DB_USER']     = 'xygbfpsg_graz'\n"
        "os.environ['DB_PASSWORD'] = 'j.ez-xy6##y.rllB'\n"
        "os.environ['DB_HOST']     = 'localhost'\n"
        "os.environ['DB_PORT']     = '3306'\n"
        "sys.path.insert(0, '" + BASE_DIR.replace('\\', '/') + "')\n"
        "import django; django.setup()\n"
        "from accounting.models import Account, JournalEntry, JournalEntryLine, FiscalPeriod\n"
        "from django.db.models import Sum\n"
        "from django.utils import timezone\n"
        "print()\n"
        "print('  Chart of Accounts:')\n"
        "for t in ['asset','liability','equity','income','expense']:\n"
        "    n = Account.objects.filter(account_type=t, is_active=True).count()\n"
        "    print(f'    {t.upper():12} {n} accounts')\n"
        "print()\n"
        "print('  Journal Entries:')\n"
        "for s in ['draft','posted','voided']:\n"
        "    n = JournalEntry.objects.filter(status=s).count()\n"
        "    print(f'    {s.upper():10} {n}')\n"
        "today = timezone.now().date()\n"
        "op = FiscalPeriod.objects.filter(start_date__lte=today, end_date__gte=today, status='open').first()\n"
        "print()\n"
        "print('  Open period today:', op.name if op else 'NONE -- entries cannot be posted!')\n"
        "dr = JournalEntryLine.objects.filter(journal_entry__status='posted').aggregate(t=Sum('debit_amount'))['t'] or 0\n"
        "cr = JournalEntryLine.objects.filter(journal_entry__status='posted').aggregate(t=Sum('credit_amount'))['t'] or 0\n"
        "print(f'  Total debits : KES {float(dr):,.2f}')\n"
        "print(f'  Total credits: KES {float(cr):,.2f}')\n"
        "print('  Balanced     :', 'YES' if abs(float(dr)-float(cr)) < 0.01 else 'NO -- investigate!')\n"
        "print()\n"
        "print('  Signal accounts (must all be OK):')\n"
        "for code in ['1010','1013','1020','4010','4020']:\n"
        "    try:\n"
        "        a = Account.objects.get(code=code, is_active=True)\n"
        "        print(f'    {code}  {a.name[:45]:45}  OK')\n"
        "    except Account.DoesNotExist:\n"
        "        print(f'    {code}  MISSING -- fix immediately')\n"
        "print()\n"
    )
    subprocess.call([PYTHON, '-c', health], env=ENV)

    print("\n" + "=" * 70)
    print("  Activation complete.")
    print("  - Loan disbursement  -> DISB- journal entry (automatic)")
    print("  - Repayment received -> REP-  journal entry (automatic)")
    print("  - Expense approved   -> EXP-  journal entry (automatic)")
    print("  - Loan fully paid    -> INT-  interest income (automatic)")
    print()
    print("  Journal : /accounting/journal/")
    print("  Reports : /accounting/reports/dashboard/")
    print("=" * 70)


if __name__ == '__main__':
    main()
