"""
run_accounting_setup.py
=======================
Standalone script — no Django, no manage.py, no settings files.
Connects directly to MySQL with hardcoded credentials.

Steps:
  1. Seeds Chart of Accounts (skips existing)
  2. Creates Fiscal Periods 2025/2026/2027 (skips existing)
  3. Backfills GL journal entries for all loans + repayments (idempotent)
  4. Health check

Run:  python run_accounting_setup.py
"""

import sys, json
from datetime import datetime, timedelta, date
from decimal import Decimal

try:
    import pymysql
except ImportError:
    import subprocess
    subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--quiet', '--user', 'pymysql'])
    import pymysql

DB = dict(
    host='localhost', port=3306,
    database='xygbfpsg_loans',
    user='xygbfpsg_graz',
    password='j.ez-xy6##y.rllB',
    charset='utf8mb4',
    cursorclass=pymysql.cursors.DictCursor,
)
SEP = '=' * 70
NOW = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')


# ── helpers ────────────────────────────────────────────────────────────────

def get_account_id(cur, code):
    cur.execute("SELECT id FROM accounting_accounts WHERE code=%s AND is_active=1", [code])
    r = cur.fetchone()
    if not r:
        raise ValueError(f"Account {code} not found — check step 1")
    return r['id']

def get_system_user(cur):
    cur.execute("SELECT id FROM users WHERE is_superuser=1 ORDER BY date_joined LIMIT 1")
    r = cur.fetchone()
    return r['id'] if r else None

def next_id(cur, table):
    """Get next autoincrement id for a table."""
    cur.execute(f"SELECT COALESCE(MAX(id),0)+1 AS nid FROM {table}")
    return cur.fetchone()['nid']


# ── Step 1: Chart of Accounts ──────────────────────────────────────────────

ACCOUNTS = [
    ('1010','Cash and Bank Balances','asset','current_asset','Cash on hand plus all bank and mobile-money balances.',1),
    ('1011','Cash on Hand','asset','current_asset','Physical petty cash held at branch offices.',1),
    ('1012','Bank Account – Main Operating','asset','current_asset','Primary commercial bank current account.',1),
    ('1013','M-Pesa / SasaPay Float','asset','current_asset','Mobile money float held in the SasaPay merchant wallet.',1),
    ('1020','Loan Portfolio – Performing','asset','loan_portfolio','Principal outstanding on current loans (Stage 1).',1),
    ('1021','Loan Portfolio – Watch (Stage 2)','asset','loan_portfolio','Principal outstanding 31-90 days past due.',1),
    ('1030','Loan Portfolio – Non-Performing','asset','loan_portfolio','Principal outstanding 90+ days past due (Stage 3).',1),
    ('1031','Allowance for Loan Losses (ECL)','asset','loan_portfolio','Expected Credit Loss reserve contra-asset.',1),
    ('1040','Interest Receivable','asset','current_asset','Accrued interest not yet collected.',1),
    ('1050','Fees and Charges Receivable','asset','current_asset','Processing fees billed but unpaid.',1),
    ('1060','Prepayments and Advances','asset','current_asset','Rent prepayments and staff advances.',0),
    ('1070','Other Current Assets','asset','current_asset','Sundry receivables.',0),
    ('1510','Property Plant and Equipment Gross','asset','fixed_asset','Cost of computers furniture fittings.',0),
    ('1511','Accumulated Depreciation PPE','asset','fixed_asset','Contra-asset: accumulated depreciation.',0),
    ('1520','Intangible Assets Gross','asset','fixed_asset','Software licences and core-banking system.',0),
    ('1521','Accumulated Amortisation Intangibles','asset','fixed_asset','Contra-asset: accumulated amortisation.',0),
    ('1530','Right-of-Use Assets','asset','fixed_asset','IFRS 16 right-of-use assets.',0),
    ('1540','Deferred Tax Asset','asset','other_asset','Tax recoverable from deductible temporary differences.',0),
    ('1550','Other Non-Current Assets','asset','other_asset','Long-term deposits.',0),
    ('2010','Borrowings Current Portion','liability','borrowings','Bank loan instalments due within 12 months.',1),
    ('2020','Interest Payable','liability','current_liability','Interest accrued on borrowings.',1),
    ('2030','Payables and Accruals','liability','current_liability','Trade creditors and accrued expenses.',1),
    ('2040','Income Tax Payable','liability','current_liability','Corporate tax payable to KRA.',1),
    ('2050','Statutory Deductions Payable','liability','current_liability','PAYE NSSF NHIF payable.',1),
    ('2060','Lease Liability Current Portion','liability','current_liability','Current IFRS 16 lease liabilities.',0),
    ('2070','Client Savings Deposits','liability','client_savings','Savings held on behalf of clients.',1),
    ('2080','Other Current Liabilities','liability','current_liability','Other short-term obligations.',0),
    ('2510','Borrowings Non-Current','liability','borrowings','Long-term bank loans.',1),
    ('2520','Lease Liability Non-Current','liability','other_liability','Non-current IFRS 16 lease liabilities.',0),
    ('2530','Deferred Tax Liability','liability','other_liability','Deferred tax from taxable temporary differences.',0),
    ('2540','Other Non-Current Liabilities','liability','other_liability','Long-term security deposits received.',0),
    ('3010','Share Capital','equity',None,'Paid-up ordinary share capital.',1),
    ('3020','Retained Earnings','equity',None,'Accumulated net profits from prior years.',1),
    ('3030','Current Year Surplus Deficit','equity',None,'Net profit or loss for the current year.',1),
    ('3040','Other Comprehensive Income Reserve','equity',None,'Cumulative OCI items.',0),
    ('4010','Interest Income Loans and Advances','income','interest_income','Interest charged on all loan products.',1),
    ('4020','Fee Income Processing Fees','income','fee_income','Loan origination processing fee.',1),
    ('4021','Fee Income Registration Fees','income','fee_income','Client registration fee.',1),
    ('4022','Fee Income Late Payment Penalties','income','fee_income','Penalty interest on overdue instalments.',1),
    ('4030','Other Operating Income','income','other_income','Insurance commissions and other non-core revenue.',0),
    ('5010','Interest Expense Borrowings','expense','interest_expense','Interest on bank loans.',1),
    ('5020','Loan Loss Provision ECL Charge','expense','loan_loss_provision','IFRS 9 impairment charge.',1),
    ('5021','Loans Written Off','expense','loan_loss_provision','Principal of unrecoverable loans.',1),
    ('5022','Bad Debt Recoveries','expense','loan_loss_provision','Cash recovered on written-off loans.',1),
    ('5030','Salaries and Wages','expense','staff_costs','Gross salaries for all staff.',1),
    ('5031','Pension and NSSF Contributions','expense','staff_costs','Employer NSSF contributions.',1),
    ('5032','NHIF and Medical Cover','expense','staff_costs','Employer NHIF and medical insurance.',1),
    ('5033','Staff Training and Development','expense','staff_costs','Training and professional development.',0),
    ('5040','Rent Expense','expense','administrative_expense','Office premises rental.',0),
    ('5041','Utilities Expense','expense','administrative_expense','Electricity water internet.',0),
    ('5042','Office Supplies and Stationery','expense','administrative_expense','Consumable office materials.',0),
    ('5043','Marketing and Advertising','expense','administrative_expense','Digital and print marketing.',0),
    ('5044','Professional and Legal Fees','expense','administrative_expense','Legal counsel and audit fees.',0),
    ('5045','Bank Charges and Commissions','expense','administrative_expense','Bank and M-Pesa transaction fees.',1),
    ('5046','Insurance Premiums','expense','administrative_expense','Credit life and other insurance.',0),
    ('5047','Travel and Transport','expense','administrative_expense','Fuel and transport.',0),
    ('5048','Communication and IT Expenses','expense','administrative_expense','Airtime data software subscriptions.',0),
    ('5050','Depreciation Property Plant Equipment','expense','depreciation','Depreciation of PPE.',0),
    ('5051','Amortisation Intangible Assets','expense','depreciation','Amortisation of software.',0),
    ('5052','Depreciation Right-of-Use Assets','expense','depreciation','IFRS 16 depreciation.',0),
    ('5060','Regulatory and Compliance Fees','expense','other_expense','CBK licence fees.',1),
    ('5061','Security and Guarding','expense','other_expense','Physical security services.',0),
    ('5062','Miscellaneous Operating Expenses','expense','other_expense','Other operating costs.',0),
    ('5070','Income Tax Expense Current','expense','taxation','Corporate tax on current-year income.',1),
    ('5071','Deferred Tax Expense Credit','expense','taxation','Movement in deferred tax balances.',1),
]

def step1_accounts(cur):
    print(SEP)
    print("  STEP 1: Chart of Accounts")
    print(SEP)
    cur.execute("SELECT id FROM users WHERE role='admin' AND is_active=1 ORDER BY date_joined LIMIT 1")
    r = cur.fetchone()
    sys_user = r['id'] if r else None
    created = skipped = 0
    for code, name, acc_type, subtype, desc, is_sys in ACCOUNTS:
        cur.execute("SELECT id FROM accounting_accounts WHERE code=%s", [code])
        if cur.fetchone():
            skipped += 1
            continue
        nid = next_id(cur, 'accounting_accounts')
        cur.execute("""
            INSERT INTO accounting_accounts
                (id, code, name, account_type, subtype, description,
                 is_active, is_system_account, created_by_id, created_at, updated_at)
            VALUES (%s,%s,%s,%s,%s,%s,1,%s,%s,%s,%s)
        """, [nid, code, name, acc_type, subtype, desc, is_sys, sys_user, NOW, NOW])
        print(f"  [+] {code:8s}  {name}")
        created += 1
    print(f"\n  Accounts: {created} created, {skipped} already existed")


# ── Step 2: Fiscal Periods ─────────────────────────────────────────────────

def step2_periods(cur):
    print()
    print(SEP)
    print("  STEP 2: Fiscal Periods")
    print(SEP)
    created = skipped = 0
    empty_json = json.dumps({})
    for year in [2025, 2026, 2027]:
        for month in range(1, 13):
            start = date(year, month, 1)
            end   = date(year, month+1, 1) - timedelta(days=1) if month < 12 else date(year, 12, 31)
            name  = start.strftime('%B %Y')
            cur.execute("SELECT id FROM accounting_fiscal_periods WHERE name=%s", [name])
            if cur.fetchone():
                skipped += 1
                continue
            nid = next_id(cur, 'accounting_fiscal_periods')
            cur.execute("""
                INSERT INTO accounting_fiscal_periods
                    (id, name, period_type, start_date, end_date, status,
                     opening_balances, closing_balances, created_at, updated_at)
                VALUES (%s,%s,'monthly',%s,%s,'open',%s,%s,%s,%s)
            """, [nid, name, start, end, empty_json, empty_json, NOW, NOW])
            print(f"  [+] {name}")
            created += 1
        fy = f'FY {year}'
        cur.execute("SELECT id FROM accounting_fiscal_periods WHERE name=%s", [fy])
        if cur.fetchone():
            skipped += 1
        else:
            nid = next_id(cur, 'accounting_fiscal_periods')
            cur.execute("""
                INSERT INTO accounting_fiscal_periods
                    (id, name, period_type, start_date, end_date, status,
                     opening_balances, closing_balances, created_at, updated_at)
                VALUES (%s,%s,'annual',%s,%s,'open',%s,%s,%s,%s)
            """, [nid, fy, date(year,1,1), date(year,12,31), empty_json, empty_json, NOW, NOW])
            print(f"  [+] {fy}")
            created += 1
    print(f"\n  Periods: {created} created, {skipped} already existed")


# ── Step 3: GL Backfill ────────────────────────────────────────────────────

def post_je(cur, ref, tx_date, description, loan_id, sys_user, lines):
    """
    Insert journal entry + lines + GL rows.
    Returns True if posted, False if already existed.
    lines = list of (account_id, debit, credit, line_desc)
    """
    cur.execute("SELECT id FROM accounting_journal_entries WHERE reference_number=%s", [ref])
    if cur.fetchone():
        return False

    if hasattr(tx_date, 'date'):
        tx_date = tx_date.date()

    je_id = next_id(cur, 'accounting_journal_entries')
    cur.execute("""
        INSERT INTO accounting_journal_entries
            (id, reference_number, transaction_date, description,
             status, loan_id, created_by_id, posted_by_id,
             created_at, updated_at, posted_at)
        VALUES (%s,%s,%s,%s,'posted',%s,%s,%s,%s,%s,%s)
    """, [je_id, ref, tx_date, description,
          loan_id, sys_user, sys_user, NOW, NOW, NOW])

    for line_num, (acc_id, debit, credit, line_desc) in enumerate(lines, 1):
        line_id = next_id(cur, 'accounting_journal_entry_lines')
        cur.execute("""
            INSERT INTO accounting_journal_entry_lines
                (id, journal_entry_id, account_id, description,
                 debit_amount, credit_amount, line_number)
            VALUES (%s,%s,%s,%s,%s,%s,%s)
        """, [line_id, je_id, acc_id, line_desc[:500], debit, credit, line_num])

        # Running balance for GL
        cur.execute("""
            SELECT balance FROM accounting_general_ledger
            WHERE account_id=%s ORDER BY transaction_date DESC, posted_at DESC LIMIT 1
        """, [acc_id])
        prev = cur.fetchone()
        prev_bal = Decimal(str(prev['balance'])) if prev else Decimal('0.00')

        cur.execute("SELECT account_type FROM accounting_accounts WHERE id=%s", [acc_id])
        acc_type = cur.fetchone()['account_type']
        if acc_type in ('asset', 'expense'):
            new_bal = prev_bal + Decimal(str(debit)) - Decimal(str(credit))
        else:
            new_bal = prev_bal + Decimal(str(credit)) - Decimal(str(debit))

        gl_id = next_id(cur, 'accounting_general_ledger')
        cur.execute("""
            INSERT INTO accounting_general_ledger
                (id, account_id, journal_entry_id, journal_entry_line_id,
                 transaction_date, description, reference_number,
                 debit_amount, credit_amount, balance,
                 posted_at, posted_by_id)
            VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
        """, [gl_id, acc_id, je_id, line_id,
              tx_date, line_desc[:500], ref,
              debit, credit, new_bal, NOW, sys_user])
    return True


def step3_backfill(cur):
    print()
    print(SEP)
    print("  STEP 3: GL Backfill")
    print(SEP)

    ACC_CASH     = get_account_id(cur, '1010')
    ACC_MPESA    = get_account_id(cur, '1013')
    ACC_LOANS    = get_account_id(cur, '1020')
    ACC_INTEREST = get_account_id(cur, '4010')
    ACC_FEES     = get_account_id(cur, '4020')
    ACC_EQUITY   = get_account_id(cur, '3010')
    sys_user     = get_system_user(cur)

    disb = fee = rep = intr = 0

    # Loans
    cur.execute("""
        SELECT id, loan_number, principal_amount, processing_fee,
               interest_amount, disbursement_date, status
        FROM loans
        WHERE status IN ('active','paid','defaulted','rolled_over','written_off')
          AND is_deleted=0 AND disbursement_date IS NOT NULL
        ORDER BY disbursement_date
    """)
    loans = cur.fetchall()
    print(f"  Loans: {len(loans)}")

    for loan in loans:
        lid  = loan['id']
        ln   = loan['loan_number']
        amt  = Decimal(str(loan['principal_amount']))
        pfee = Decimal(str(loan['processing_fee'] or 0))
        iamt = Decimal(str(loan['interest_amount'] or 0))
        dt   = loan['disbursement_date']

        if post_je(cur, f'DISB-{ln}', dt,
                   f'Loan Disbursement - {ln}', lid, sys_user,
                   [(ACC_LOANS, amt, 0,   f'Loan disbursed - {ln}'),
                    (ACC_CASH,  0,   amt, f'Cash out - {ln}')]):
            disb += 1
            print(f"  POST DISB-{ln}  KES {amt:,.0f}")

        if pfee > 0:
            if post_je(cur, f'FEE-{ln}', dt,
                       f'Processing Fee - {ln}', lid, sys_user,
                       [(ACC_CASH, pfee, 0,    f'Fee received - {ln}'),
                        (ACC_FEES, 0,    pfee, f'Fee income - {ln}')]):
                fee += 1
                print(f"  POST FEE-{ln}   KES {pfee:,.0f}")

        if loan['status'] == 'paid' and iamt > 0:
            if post_je(cur, f'INT-{ln}', dt,
                       f'Interest Income - {ln}', lid, sys_user,
                       [(ACC_CASH,     iamt, 0,     f'Interest income - {ln}'),
                        (ACC_INTEREST, 0,    iamt,  f'Interest income - {ln}')]):
                intr += 1
                print(f"  POST INT-{ln}   KES {iamt:,.0f}")

    # Repayments
    cur.execute("""
        SELECT id, receipt_number, amount, payment_date,
               payment_method, payment_source, loan_id
        FROM repayments ORDER BY payment_date
    """)
    repayments = cur.fetchall()
    print(f"\n  Repayments: {len(repayments)}")

    for r in repayments:
        ref  = f"REP-{r['receipt_number'] or r['id']}"
        amt  = Decimal(str(r['amount']))
        dt   = r['payment_date']
        is_mpesa = (r['payment_method'] == 'mpesa' or r['payment_source'] == 'automatic')
        cash = ACC_MPESA if is_mpesa else ACC_CASH

        if post_je(cur, ref, dt,
                   f"Repayment - {r['loan_id']}", r['loan_id'], sys_user,
                   [(cash,     amt, 0,   f"Payment received - {r['payment_method']}"),
                    (ACC_LOANS, 0,  amt, f"Loan repaid - {r['loan_id']}")]):
            rep += 1
            if rep % 50 == 0:
                print(f"  ... {rep} repayments posted")

    # Opening equity
    cur.execute("SELECT COALESCE(SUM(principal_amount),0) AS t FROM loans WHERE is_deleted=0")
    total_out = Decimal(str(cur.fetchone()['t']))
    cur.execute("SELECT COALESCE(SUM(amount),0) AS t FROM repayments")
    total_in  = Decimal(str(cur.fetchone()['t']))
    cash_bal  = total_in - total_out

    if cash_bal < 0:
        eq_amt = abs(cash_bal)
        cur.execute("SELECT MIN(disbursement_date) AS d FROM loans WHERE is_deleted=0 AND disbursement_date IS NOT NULL")
        earliest = cur.fetchone()['d']
        eq_date  = (earliest - timedelta(days=1)) if earliest else date(2025, 1, 1)
        if post_je(cur, 'OPEN-EQUITY-001', eq_date,
                   'Opening capital - equity injection', None, sys_user,
                   [(ACC_CASH,   eq_amt, 0,      'Opening capital'),
                    (ACC_EQUITY, 0,      eq_amt, 'Opening capital')]):
            print(f"  POST OPEN-EQUITY-001  KES {eq_amt:,.0f}")

    print(f"\n  Posted: {disb} disbursements, {rep} repayments, {fee} fees, {intr} interest entries")


# ── Step 4: Health check ───────────────────────────────────────────────────

def step4_health(cur):
    print()
    print(SEP)
    print("  STEP 4: Health Check")
    print(SEP)

    cur.execute("SELECT account_type, COUNT(*) n FROM accounting_accounts WHERE is_active=1 GROUP BY account_type")
    print("\n  Accounts by type:")
    for r in cur.fetchall():
        print(f"    {r['account_type'].upper():15s}  {r['n']}")

    cur.execute("SELECT status, COUNT(*) n FROM accounting_journal_entries GROUP BY status")
    print("\n  Journal entries:")
    for r in cur.fetchall():
        print(f"    {r['status'].upper():12s}  {r['n']}")

    today = date.today()
    cur.execute("""
        SELECT name FROM accounting_fiscal_periods
        WHERE start_date<=%s AND end_date>=%s AND status='open' AND period_type='monthly' LIMIT 1
    """, [today, today])
    r = cur.fetchone()
    print(f"\n  Open period today: {r['name'] if r else 'NONE'}")

    cur.execute("""
        SELECT COALESCE(SUM(l.debit_amount),0) dr, COALESCE(SUM(l.credit_amount),0) cr
        FROM accounting_journal_entry_lines l
        JOIN accounting_journal_entries e ON e.id=l.journal_entry_id
        WHERE e.status='posted'
    """)
    r = cur.fetchone()
    dr = Decimal(str(r['dr'])); cr = Decimal(str(r['cr']))
    print(f"\n  Total debits : KES {dr:>15,.2f}")
    print(f"  Total credits: KES {cr:>15,.2f}")
    print(f"  Balanced     : {'YES' if abs(dr-cr) < Decimal('0.01') else 'NO - investigate!'}")

    print("\n  Signal accounts:")
    for code in ['1010','1013','1020','4010','4020']:
        cur.execute("SELECT name FROM accounting_accounts WHERE code=%s AND is_active=1", [code])
        r = cur.fetchone()
        print(f"    {code}  {r['name'][:45] if r else 'MISSING'}")
    print()


# ── Main ───────────────────────────────────────────────────────────────────

def main():
    print(); print(SEP)
    print("  Haven Grazuri - Accounting Setup (standalone)")
    print(SEP)

    conn = pymysql.connect(**DB)
    try:
        with conn.cursor() as cur:
            step1_accounts(cur); conn.commit()
            step2_periods(cur);  conn.commit()
            step3_backfill(cur); conn.commit()
            step4_health(cur)
    finally:
        conn.close()

    print(SEP)
    print("  Done. Accounting module is live.")
    print(SEP)

if __name__ == '__main__':
    main()
