import sys
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
conn = pymysql.connect(**DB)
cur  = conn.cursor()

print(f'\n{SEP}')
print('  Loan Report Diagnostic — Part 2')
print(SEP)

# 3. Check amount_paid cache vs actual repayments (using correct column name)
print('\n3. amount_paid cache vs actual repayments SUM\n')
cur.execute("""
    SELECT
        l.loan_number,
        l.amount_paid AS cached_paid,
        COALESCE(SUM(r.amount), 0) AS actual_paid,
        ABS(l.amount_paid - COALESCE(SUM(r.amount), 0)) AS diff
    FROM loans l
    LEFT JOIN repayments r ON r.loan_id = l.id
    WHERE l.is_deleted = 0
    GROUP BY l.id, l.loan_number, l.amount_paid
    HAVING diff > 0.01
    LIMIT 20
""")
mismatches = cur.fetchall()
if mismatches:
    print(f'  FOUND {len(mismatches)} loans where cached amount_paid != actual sum:')
    print(f'  {"Loan":25s}  {"Cached":>12}  {"Actual DB":>12}  {"Diff":>10}')
    for r in mismatches:
        print(f"  {r['loan_number']:25s}  {Decimal(str(r['cached_paid'])):>12,.2f}  "
              f"{Decimal(str(r['actual_paid'])):>12,.2f}  "
              f"{Decimal(str(r['diff'])):>10,.2f}")
else:
    print('  No mismatches — amount_paid cache is accurate for all loans.')

# 4. Monthly totals — Sep and Oct 2026
print('\n\n4. DISBURSED LOANS — Sep & Oct 2026 Detail\n')
for label, start, end in [
    ('September 2026', '2026-09-01', '2026-09-30'),
    ('October 2026',   '2026-10-01', '2026-10-31'),
]:
    cur.execute("""
        SELECT COUNT(*) cnt,
               SUM(l.principal_amount) sum_principal,
               SUM(l.total_amount) sum_total,
               SUM(l.interest_amount) sum_interest,
               SUM(l.processing_fee) sum_fee,
               SUM(l.amount_paid) sum_cached_paid,
               COALESCE((SELECT SUM(r.amount) FROM repayments r
                          WHERE r.loan_id IN
                            (SELECT id FROM loans WHERE is_deleted=0
                             AND status IN ('active','paid','defaulted','rolled_over','written_off')
                             AND disbursement_date BETWEEN %s AND %s)), 0) sum_actual_paid
        FROM loans l
        WHERE l.is_deleted=0
          AND l.status IN ('active','paid','defaulted','rolled_over','written_off')
          AND l.disbursement_date BETWEEN %s AND %s
    """, [start, end+' 23:59:59', start, end+' 23:59:59'])
    r = cur.fetchone()
    prin  = Decimal(str(r['sum_principal'] or 0))
    total = Decimal(str(r['sum_total'] or 0))
    intr  = Decimal(str(r['sum_interest'] or 0))
    fee   = Decimal(str(r['sum_fee'] or 0))
    c_paid = Decimal(str(r['sum_cached_paid'] or 0))
    a_paid = Decimal(str(r['sum_actual_paid'] or 0))
    print(f'  {label} ({r["cnt"]} loans):')
    print(f'    Principal amount (cash disbursed)  : KES {prin:>12,.2f}  <- what admin counts')
    print(f'    Total amount (princ+interest+fee)  : KES {total:>12,.2f}  <- what report may show')
    print(f'    Interest component                 : KES {intr:>12,.2f}')
    print(f'    Processing fees                    : KES {fee:>12,.2f}')
    print(f'    Amount repaid (cached field)       : KES {c_paid:>12,.2f}')
    print(f'    Amount repaid (actual DB sum)      : KES {a_paid:>12,.2f}')
    print(f'    Outstanding (principal - actual)   : KES {max(prin - a_paid, Decimal("0")):>12,.2f}')
    print()

# 5. Key finding summary
print('\n5. KEY FINDING\n')
cur.execute("""
    SELECT SUM(principal_amount) sp, SUM(total_amount) st, SUM(interest_amount) si
    FROM loans WHERE is_deleted=0 AND status IN ('active','paid','defaulted','rolled_over','written_off')
""")
r = cur.fetchone()
sp = Decimal(str(r['sp'] or 0))
st = Decimal(str(r['st'] or 0))
si = Decimal(str(r['si'] or 0))
print(f'  All disbursed loans:')
print(f'    Sum principal_amount : KES {sp:>12,.2f}  (cash given to customers)')
print(f'    Sum total_amount     : KES {st:>12,.2f}  (includes interest)')
print(f'    Sum interest_amount  : KES {si:>12,.2f}')
print()
print(f'  Section 1 showed "total_amount" sum = KES 12,657,059')
print(f'  But "principal_amount" sum = KES {sp:>12,.2f}')
print()
print('  The DATE_FORMAT bug in Section 1 (%%Y-%%m returning literal text) means')
print('  the month grouping was broken — all records lumped into one row.')
print('  The actual months need fixing in the GROUP BY.')

# Fix: proper monthly breakdown
print('\n\n6. CORRECTED MONTHLY BREAKDOWN\n')
cur.execute("""
    SELECT
        YEAR(disbursement_date) yr,
        MONTH(disbursement_date) mo,
        COUNT(*) cnt,
        SUM(principal_amount) sum_principal,
        SUM(total_amount) sum_total
    FROM loans
    WHERE is_deleted=0
      AND disbursement_date >= '2026-01-01'
      AND status IN ('active','paid','defaulted','rolled_over','written_off')
    GROUP BY YEAR(disbursement_date), MONTH(disbursement_date)
    ORDER BY yr DESC, mo DESC
""")
rows = cur.fetchall()
print(f'  {"Month":12s}  {"Loans":>6}  {"Principal KES":>14}  {"Total Amt KES":>14}')
print(f'  {"-"*12}  {"-"*6}  {"-"*14}  {"-"*14}')
for r in rows:
    import calendar
    month_name = f'{calendar.month_abbr[r["mo"]]} {r["yr"]}'
    print(f'  {month_name:12s}  {r["cnt"]:>6}  '
          f'{Decimal(str(r["sum_principal"] or 0)):>14,.2f}  '
          f'{Decimal(str(r["sum_total"] or 0)):>14,.2f}')

conn.close()
print(f'\n{SEP}')
print('  Done.')
print(SEP)
