"""
verify_accounting.py
====================
Comprehensive accounting verification script.
Checks every layer: data integrity, signal wiring, report calculations,
cross-validation against actual loan/repayment data.

Run:  python verify_accounting.py
"""
import sys
from datetime import 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  = '=' * 72
SEP2 = '-' * 72
PASS = 'PASS'
FAIL = 'FAIL'
WARN = 'WARN'

results = []

def check(label, status, detail=''):
    icon = {'PASS':'OK  ','FAIL':'FAIL','WARN':'WARN'}[status]
    line = f"  [{icon}] {label}"
    if detail:
        line += f"\n         {detail}"
    print(line)
    results.append((status, label, detail))

def D(v):
    return Decimal(str(v or 0))

conn = pymysql.connect(**DB)
cur  = conn.cursor()

print()
print(SEP)
print("  Haven Grazuri — Accounting Full Verification")
print(SEP)

# ═══════════════════════════════════════════════════════════════════════════
# 1. CHART OF ACCOUNTS
# ═══════════════════════════════════════════════════════════════════════════
print(f"\n{'1. CHART OF ACCOUNTS':}")
print(SEP2)

REQUIRED = {
    '1010': ('asset',  'Cash and Bank Balances'),
    '1013': ('asset',  'M-Pesa / SasaPay Float'),
    '1020': ('asset',  'Loan Portfolio'),
    '4010': ('income', 'Interest Income'),
    '4020': ('income', 'Fee Income'),
    '3010': ('equity', 'Share Capital'),
}
for code, (acc_type, label) in REQUIRED.items():
    cur.execute("SELECT id, name, account_type, is_active FROM accounting_accounts WHERE code=%s", [code])
    r = cur.fetchone()
    if not r:
        check(f"Account {code} ({label})", FAIL, "Missing — signals will crash")
    elif not r['is_active']:
        check(f"Account {code} {r['name']}", FAIL, "Exists but is_active=0 — signals will crash")
    elif r['account_type'] != acc_type:
        check(f"Account {code} {r['name']}", WARN, f"Type is '{r['account_type']}' expected '{acc_type}'")
    else:
        check(f"Account {code} — {r['name']}", PASS)

cur.execute("SELECT COUNT(*) n FROM accounting_accounts WHERE is_active=1")
total_accs = cur.fetchone()['n']
check(f"Total active accounts: {total_accs}", PASS if total_accs >= 60 else WARN,
      "" if total_accs >= 60 else "Expected 60+")

# ═══════════════════════════════════════════════════════════════════════════
# 2. FISCAL PERIODS
# ═══════════════════════════════════════════════════════════════════════════
print(f"\n2. FISCAL PERIODS")
print(SEP2)

today = date.today()
cur.execute("""
    SELECT name, status FROM accounting_fiscal_periods
    WHERE start_date <= %s AND end_date >= %s AND period_type='monthly'
    LIMIT 1
""", [today, today])
r = cur.fetchone()
if not r:
    check(f"Open period covering {today}", FAIL, "No open monthly period — new journal entries CANNOT be posted")
elif r['status'] != 'open':
    check(f"Period {r['name']} covering today", FAIL, f"Status is '{r['status']}' not 'open'")
else:
    check(f"Open period: {r['name']}", PASS)

cur.execute("SELECT COUNT(*) n FROM accounting_fiscal_periods WHERE status='open'")
open_periods = cur.fetchone()['n']
check(f"Open fiscal periods: {open_periods}", PASS if open_periods >= 12 else WARN)

# ═══════════════════════════════════════════════════════════════════════════
# 3. DOUBLE-ENTRY INTEGRITY
# ═══════════════════════════════════════════════════════════════════════════
print(f"\n3. DOUBLE-ENTRY INTEGRITY")
print(SEP2)

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()
total_dr = D(r['dr']); total_cr = D(r['cr'])
diff = abs(total_dr - total_cr)
check(f"Total debits  = KES {total_dr:>15,.2f}", PASS)
check(f"Total credits = KES {total_cr:>15,.2f}", PASS)
check(f"Debits == Credits (diff={diff})", PASS if diff < D('0.01') else FAIL,
      "" if diff < D('0.01') else f"Out of balance by KES {diff:,.2f}")

# Check individual entries that are unbalanced
cur.execute("""
    SELECT e.reference_number,
           SUM(l.debit_amount) dr, SUM(l.credit_amount) cr,
           ABS(SUM(l.debit_amount) - SUM(l.credit_amount)) diff
    FROM accounting_journal_entries e
    JOIN accounting_journal_entry_lines l ON l.journal_entry_id=e.id
    WHERE e.status='posted'
    GROUP BY e.id, e.reference_number
    HAVING diff > 0.01
    LIMIT 10
""")
bad = cur.fetchall()
if bad:
    check(f"Unbalanced journal entries: {len(bad)}", FAIL,
          "  " + ", ".join(r['reference_number'] for r in bad))
else:
    check("All individual journal entries balanced", PASS)

# ═══════════════════════════════════════════════════════════════════════════
# 4. JOURNAL ENTRY COVERAGE
# ═══════════════════════════════════════════════════════════════════════════
print(f"\n4. JOURNAL ENTRY COVERAGE")
print(SEP2)

# Active + paid loans should all have a DISB- entry
cur.execute("""
    SELECT l.loan_number
    FROM loans l
    LEFT JOIN accounting_journal_entries je
        ON je.reference_number = CONCAT('DISB-', l.loan_number)
    WHERE l.status IN ('active','paid','defaulted')
      AND l.is_deleted=0
      AND l.disbursement_date IS NOT NULL
      AND je.id IS NULL
""")
missing_disb = cur.fetchall()
if missing_disb:
    check(f"Loans missing DISB- entry: {len(missing_disb)}", FAIL,
          "Examples: " + ", ".join(r['loan_number'] for r in missing_disb[:5]))
else:
    check("All disbursed loans have DISB- journal entry", PASS)

# All repayments should have a REP- entry
cur.execute("""
    SELECT r.receipt_number
    FROM repayments r
    LEFT JOIN accounting_journal_entries je
        ON je.reference_number = CONCAT('REP-', r.receipt_number)
    WHERE je.id IS NULL
    LIMIT 20
""")
missing_rep = cur.fetchall()
if missing_rep:
    check(f"Repayments missing REP- entry: {len(missing_rep)}", FAIL,
          "Examples: " + ", ".join(r['receipt_number'] for r in missing_rep[:5]))
else:
    check("All repayments have REP- journal entry", PASS)

# Paid loans should have INT- entry
cur.execute("""
    SELECT l.loan_number, l.interest_amount
    FROM loans l
    LEFT JOIN accounting_journal_entries je
        ON je.reference_number = CONCAT('INT-', l.loan_number)
    WHERE l.status='paid' AND l.interest_amount > 0
      AND l.is_deleted=0 AND je.id IS NULL
""")
missing_int = cur.fetchall()
if missing_int:
    check(f"Paid loans missing INT- entry: {len(missing_int)}", WARN,
          "Examples: " + ", ".join(r['loan_number'] for r in missing_int[:5]))
else:
    check("All paid loans have INT- interest recognition entry", PASS)

# Count breakdown
cur.execute("SELECT LEFT(reference_number,4) prefix, COUNT(*) n FROM accounting_journal_entries GROUP BY prefix ORDER BY n DESC")
print("\n  Entry type breakdown:")
for r in cur.fetchall():
    print(f"    {r['prefix']:10s}  {r['n']:>5} entries")

# ═══════════════════════════════════════════════════════════════════════════
# 5. LOAN PORTFOLIO BALANCE CROSS-CHECK
# ═══════════════════════════════════════════════════════════════════════════
print(f"\n5. LOAN PORTFOLIO BALANCE CROSS-CHECK")
print(SEP2)

# What the GL says the loan portfolio balance is
cur.execute("""
    SELECT g.balance
    FROM accounting_general_ledger g
    JOIN accounting_accounts a ON a.id=g.account_id
    WHERE a.code='1020'
    ORDER BY g.transaction_date DESC, g.posted_at DESC
    LIMIT 1
""")
r = cur.fetchone()
gl_portfolio = D(r['balance']) if r else D('0')

# Cross-check using GL entries only — disbursements posted vs repayments posted
# (loans.amount_paid is a denormalised cache field and is NOT the source of truth)
cur.execute("""
    SELECT COALESCE(SUM(l.debit_amount),0) gl_disb
    FROM accounting_journal_entries e
    JOIN accounting_journal_entry_lines l ON l.journal_entry_id=e.id
    JOIN accounting_accounts a ON a.id=l.account_id
    WHERE e.reference_number LIKE 'DISB-%' AND a.code='1020'
""")
gl_disb = D(cur.fetchone()['gl_disb'])

cur.execute("""
    SELECT COALESCE(SUM(l.credit_amount),0) gl_rep
    FROM accounting_journal_entries e
    JOIN accounting_journal_entry_lines l ON l.journal_entry_id=e.id
    JOIN accounting_accounts a ON a.id=l.account_id
    WHERE e.reference_number LIKE 'REP-%' AND a.code='1020'
""")
gl_rep = D(cur.fetchone()['gl_rep'])

gl_expected = gl_disb - gl_rep
diff = abs(gl_portfolio - gl_expected)

check(f"GL Loan Portfolio balance  : KES {gl_portfolio:>15,.2f}", PASS)
check(f"GL DISB debits - REP credits: KES {gl_expected:>14,.2f}", PASS)
check(f"GL internal consistency (diff={diff:,.2f})",
      PASS if diff < D('1') else WARN if diff < D('100') else FAIL,
      "" if diff < D('1') else f"Discrepancy KES {diff:,.2f} — GL running balance may need recalculation")

# Also show actual repayments table total for reference
cur.execute("SELECT COALESCE(SUM(amount),0) t FROM repayments")
actual_rep_total = D(cur.fetchone()['t'])
check(f"Repayments table total      : KES {actual_rep_total:>15,.2f}  (reference only — includes pre-accounting history)", PASS)

# ═══════════════════════════════════════════════════════════════════════════
# 6. INCOME STATEMENT FIGURES
# ═══════════════════════════════════════════════════════════════════════════
print(f"\n6. INCOME STATEMENT FIGURES")
print(SEP2)

cur.execute("""
    SELECT a.code, a.name,
           COALESCE(SUM(l.credit_amount),0) - COALESCE(SUM(l.debit_amount),0) AS balance
    FROM accounting_accounts a
    LEFT JOIN accounting_general_ledger l ON l.account_id=a.id
    WHERE a.account_type='income' AND a.is_active=1
    GROUP BY a.id, a.code, a.name
    ORDER BY a.code
""")
income_rows = cur.fetchall()
total_income = D('0')
print("  Income accounts:")
for r in income_rows:
    bal = D(r['balance'])
    total_income += bal
    flag = '' if bal >= 0 else '  <-- NEGATIVE (check)'
    print(f"    {r['code']:8s}  {r['name'][:40]:40s}  KES {bal:>12,.2f}{flag}")
print(f"  {'':50s}  {'':3s} {'-'*14}")
print(f"  {'TOTAL INCOME':50s}      KES {total_income:>12,.2f}")

# Cross-check: total interest income vs sum of interest_amount on paid loans
cur.execute("SELECT COALESCE(SUM(interest_amount),0) t FROM loans WHERE status='paid' AND is_deleted=0")
actual_interest = D(cur.fetchone()['t'])

cur.execute("""
    SELECT COALESCE(SUM(l.credit_amount),0) t
    FROM accounting_general_ledger l
    JOIN accounting_accounts a ON a.id=l.account_id
    WHERE a.code='4010'
""")
gl_interest = D(cur.fetchone()['t'])
diff_int = abs(gl_interest - actual_interest)
check(f"Interest income in GL   : KES {gl_interest:>12,.2f}", PASS)
check(f"Interest on paid loans  : KES {actual_interest:>12,.2f}", PASS)
check(f"Interest income matches paid loans",
      PASS if diff_int < D('100') else WARN,
      "" if diff_int < D('100') else f"Diff KES {diff_int:,.2f} — some paid loans may lack INT- entry")

# ═══════════════════════════════════════════════════════════════════════════
# 7. BALANCE SHEET FIGURES
# ═══════════════════════════════════════════════════════════════════════════
print(f"\n7. BALANCE SHEET FIGURES")
print(SEP2)

for section, codes in [
    ("Assets",      ['1010','1011','1012','1013','1020','1021','1030']),
    ("Liabilities", ['2010','2020','2030','2040','2050','2070']),
    ("Equity",      ['3010','3020','3030']),
]:
    placeholders = ','.join(['%s']*len(codes))
    cur.execute(f"""
        SELECT a.code, a.name, a.account_type,
               COALESCE(SUM(l.debit_amount),0)  dr,
               COALESCE(SUM(l.credit_amount),0) cr
        FROM accounting_accounts a
        LEFT JOIN accounting_general_ledger l ON l.account_id=a.id
        WHERE a.code IN ({placeholders}) AND a.is_active=1
        GROUP BY a.id, a.code, a.name, a.account_type
        ORDER BY a.code
    """, codes)
    rows = cur.fetchall()
    total = D('0')
    print(f"  {section}:")
    for r in rows:
        if r['account_type'] in ('asset','expense'):
            bal = D(r['dr']) - D(r['cr'])
        else:
            bal = D(r['cr']) - D(r['dr'])
        total += bal
        print(f"    {r['code']:8s}  {r['name'][:38]:38s}  KES {bal:>12,.2f}")
    print(f"    {'Total '+section:47s}  KES {total:>12,.2f}\n")

# Accounting equation: Assets = Liabilities + Equity
cur.execute("""
    SELECT a.account_type,
           COALESCE(SUM(CASE WHEN a.account_type IN ('asset','expense') THEN l.debit_amount-l.credit_amount
                              ELSE l.credit_amount-l.debit_amount END),0) AS balance
    FROM accounting_accounts a
    LEFT JOIN accounting_general_ledger l ON l.account_id=a.id
    WHERE a.is_active=1
    GROUP BY a.account_type
""")
balances = {r['account_type']: D(r['balance']) for r in cur.fetchall()}
assets = balances.get('asset', D('0'))
liab   = balances.get('liability', D('0'))
equity = balances.get('equity', D('0'))
income   = balances.get('income', D('0'))
expenses = balances.get('expense', D('0'))
net_income = income - expenses
# Correct equation: Assets = Liabilities + Equity + Net Income
# Net income sits in temporary income/expense accounts until year-end close
diff_eq = abs(assets - (liab + equity + net_income))
check(f"Assets = Liab + Equity + Net Income  (diff={diff_eq:,.2f})",
      PASS if diff_eq < D('1') else WARN if diff_eq < D('1000') else FAIL,
      f"Assets={assets:,.0f}  Liab={liab:,.0f}  Equity={equity:,.0f}  Net={net_income:,.0f}")

# ═══════════════════════════════════════════════════════════════════════════
# 8. SIGNAL WIRING CHECK (recent transactions)
# ═══════════════════════════════════════════════════════════════════════════
print(f"\n8. RECENT TRANSACTION SIGNAL CHECK")
print(SEP2)

# Last 5 repayments — do they all have a journal entry?
cur.execute("""
    SELECT r.receipt_number, r.amount, r.payment_date, r.payment_source
    FROM repayments r ORDER BY r.payment_date DESC, r.created_at DESC LIMIT 5
""")
recent_reps = cur.fetchall()
print("  Last 5 repayments:")
all_ok = True
for r in recent_reps:
    ref = f"REP-{r['receipt_number']}"
    cur.execute("SELECT id FROM accounting_journal_entries WHERE reference_number=%s", [ref])
    has_je = cur.fetchone() is not None
    src = r['payment_source'] or 'manual'
    status = PASS if has_je else FAIL
    if not has_je:
        all_ok = False
    check(f"  {ref}  KES {D(r['amount']):>9,.0f}  {str(r['payment_date'])[:10]}  [{src}]",
          status,
          "" if has_je else "Missing journal entry — signal not firing!")
if all_ok:
    check("Repayment signals firing correctly for recent repayments", PASS)

# Last 3 disbursed loans
cur.execute("""
    SELECT loan_number, principal_amount, disbursement_date
    FROM loans WHERE disbursement_date IS NOT NULL AND is_deleted=0
    ORDER BY disbursement_date DESC LIMIT 3
""")
recent_loans = cur.fetchall()
print("\n  Last 3 disbursed loans:")
all_ok = True
for l in recent_loans:
    ref = f"DISB-{l['loan_number']}"
    cur.execute("SELECT id FROM accounting_journal_entries WHERE reference_number=%s", [ref])
    has_je = cur.fetchone() is not None
    status = PASS if has_je else FAIL
    if not has_je:
        all_ok = False
    check(f"  {ref}  KES {D(l['principal_amount']):>10,.0f}  {str(l['disbursement_date'])[:10]}",
          status, "" if has_je else "Missing — disbursement signal not firing!")
if all_ok:
    check("Disbursement signals firing correctly for recent loans", PASS)

# ═══════════════════════════════════════════════════════════════════════════
# 9. REPORT VIEWS STATUS
# ═══════════════════════════════════════════════════════════════════════════
print(f"\n9. REPORT VIEWS STATUS")
print(SEP2)

# Check accounting views.py for TODO stubs
try:
    with open('accounting/views.py', 'r') as f:
        views_content = f.read()
    todo_views = []
    for view_name in ['trial_balance_report','income_statement_report',
                      'balance_sheet_report','cash_flow_report','reports_dashboard']:
        if f"def {view_name}" in views_content:
            # Check if it's a stub (redirects with "coming soon")
            idx = views_content.index(f"def {view_name}")
            snippet = views_content[idx:idx+300]
            if 'coming soon' in snippet or 'TODO' in snippet:
                todo_views.append(view_name)

    if todo_views:
        check(f"Report views with TODO stubs: {len(todo_views)}", FAIL,
              "These views show 'coming soon' instead of real data:\n         " +
              "\n         ".join(todo_views) +
              "\n         These need to be implemented to show accounting data in the UI.")
    else:
        check("All report views implemented (no TODO stubs)", PASS)
except Exception as e:
    check("Could not read accounting/views.py", WARN, str(e))

# ═══════════════════════════════════════════════════════════════════════════
# 10. SUMMARY
# ═══════════════════════════════════════════════════════════════════════════
print()
print(SEP)
print("  SUMMARY")
print(SEP)

passes  = sum(1 for s,_,_ in results if s == PASS)
warns   = sum(1 for s,_,_ in results if s == WARN)
fails   = sum(1 for s,_,_ in results if s == FAIL)

print(f"\n  Total checks : {len(results)}")
print(f"  Passed       : {passes}")
print(f"  Warnings     : {warns}")
print(f"  Failures     : {fails}")

if fails == 0 and warns == 0:
    print("\n  ALL CHECKS PASSED. Accounting is fully operational.")
elif fails == 0:
    print("\n  No failures. Review warnings above.")
else:
    print("\n  FAILURES FOUND. Items to fix:")
    for s, label, detail in results:
        if s == FAIL:
            print(f"    - {label}")
            if detail:
                print(f"      {detail}")

print()
conn.close()

