"""
diagnose_loan_reports.py
========================
Diagnose wrong loan totals in the disbursed loans report.
Checks: date filtering, amount calculations, total_amount vs principal_amount confusion.

Run on server:  python diagnose_loan_reports.py
"""
import sys
from decimal import Decimal
from datetime import date, datetime

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')
print(SEP)

# ── 1. Monthly breakdown of loans given ──────────────────────────────────
print('\n1. LOANS GIVEN BY MONTH (last 12 months)\n')
print(f'  {"Month":15s}  {"Count":>6}  {"Principal (KES)":>16}  {"Total Amount (KES)":>18}  {"Diff":>12}')
print(f'  {"-"*15}  {"-"*6}  {"-"*16}  {"-"*18}  {"-"*12}')
cur.execute("""
    SELECT
        DATE_FORMAT(disbursement_date, '%%Y-%%m') AS month,
        COUNT(*) AS cnt,
        SUM(principal_amount) AS total_principal,
        SUM(total_amount) AS total_amount
    FROM loans
    WHERE is_deleted=0
      AND disbursement_date >= DATE_SUB(NOW(), INTERVAL 12 MONTH)
    GROUP BY DATE_FORMAT(disbursement_date, '%%Y-%%m')
    ORDER BY month DESC
""")
for r in cur.fetchall():
    principal = Decimal(str(r['total_principal'] or 0))
    total = Decimal(str(r['total_amount'] or 0))
    diff = total - principal
    print(f"  {r['month']:15s}  {r['cnt']:>6}  {principal:>16,.2f}  {total:>18,.2f}  {diff:>12,.2f}")

# ── 2. What "total_amount" actually contains ──────────────────────────────
print('\n\n2. WHAT IS total_amount vs principal_amount?\n')
cur.execute("""
    SELECT
        loan_number, principal_amount, total_amount, interest_amount, processing_fee,
        (total_amount - principal_amount) AS difference
    FROM loans
    WHERE is_deleted=0
    ORDER BY disbursement_date DESC
    LIMIT 10
""")
print(f'  {"Loan":25s}  {"Principal":>12}  {"Total Amt":>12}  {"Interest":>10}  {"Fee":>8}  {"Diff":>10}')
print(f'  {"-"*25}  {"-"*12}  {"-"*12}  {"-"*10}  {"-"*8}  {"-"*10}')
for r in cur.fetchall():
    print(f"  {r['loan_number']:25s}  {Decimal(str(r['principal_amount'])):>12,.2f}  "
          f"{Decimal(str(r['total_amount'])):>12,.2f}  "
          f"{Decimal(str(r['interest_amount'] or 0)):>10,.2f}  "
          f"{Decimal(str(r['processing_fee'] or 0)):>8,.2f}  "
          f"{Decimal(str(r['difference'] or 0)):>10,.2f}")

# ── 3. Check amount_paid cache vs actual repayments ───────────────────────
print('\n\n3. _amount_paid_cache vs actual repayments SUM\n')
cur.execute("""
    SELECT
        l.loan_number,
        l._amount_paid_cache AS cached_paid,
        COALESCE(SUM(r.amount), 0) AS actual_paid,
        ABS(l._amount_paid_cache - 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_cache
    HAVING diff > 0.01
    LIMIT 20
""")
mismatches = cur.fetchall()
if mismatches:
    print(f'  Found {len(mismatches)} loans where cache != actual:')
    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 found — cache is accurate.')

# ── 4. Disbursed loans report totals for Sep and Oct 2026 ─────────────────
print('\n\n4. DISBURSED LOANS REPORT — Sep/Oct 2026 Totals\n')
for label, start, end in [
    ('September 2026', '2026-09-01', '2026-09-30'),
    ('October 2026',   '2026-10-01', '2026-10-31'),
    ('All time',       '2020-01-01', '2026-12-31'),
]:
    cur.execute("""
        SELECT
            COUNT(*) cnt,
            SUM(principal_amount) total_principal,
            SUM(total_amount) total_amount,
            SUM(interest_amount) total_interest,
            SUM(processing_fee) total_fee,
            COALESCE(SUM(r.amount),0) total_repaid
        FROM loans l
        LEFT JOIN repayments r ON r.loan_id = l.id
        WHERE l.is_deleted=0
          AND l.disbursement_date >= %s
          AND l.disbursement_date <= %s
          AND l.status IN ('active','paid','defaulted','rolled_over','written_off')
    """, [start, end + ' 23:59:59'])
    r = cur.fetchone()
    print(f'  {label}:')
    print(f'    Loans disbursed   : {r["cnt"]}')
    print(f'    Principal (sum)   : KES {Decimal(str(r["total_principal"] or 0)):>12,.2f}')
    print(f'    Total Amount (sum): KES {Decimal(str(r["total_amount"] or 0)):>12,.2f}  (includes interest + fee)')
    print(f'    Interest (sum)    : KES {Decimal(str(r["total_interest"] or 0)):>12,.2f}')
    print(f'    Processing Fee    : KES {Decimal(str(r["total_fee"] or 0)):>12,.2f}')
    print(f'    Repaid (actual)   : KES {Decimal(str(r["total_repaid"] or 0)):>12,.2f}')
    principal = Decimal(str(r["total_principal"] or 0))
    repaid = Decimal(str(r["total_repaid"] or 0))
    print(f'    Outstanding       : KES {max(principal - repaid, Decimal("0")):>12,.2f}')
    print()

# ── 5. The specific issue — what does the report show vs what it should ───
print('\n5. ROOT CAUSE CHECK — What "Loan Amount" the report shows\n')
print('  The disbursed_loans_report uses loan.total_amount in the table.')
print('  total_amount = principal + interest + fees (the FULL loan obligation)')
print('  But "loans given" typically means the PRINCIPAL disbursed (cash given to customer)')
print()
cur.execute("""
    SELECT
        SUM(principal_amount) as sum_principal,
        SUM(total_amount) as sum_total,
        SUM(total_amount - principal_amount) as sum_interest_fees
    FROM loans
    WHERE is_deleted=0
      AND status IN ('active','paid','defaulted','rolled_over','written_off')
""")
r = cur.fetchone()
print(f'  All active/paid loans:')
print(f'    Sum of principal_amount: KES {Decimal(str(r["sum_principal"] or 0)):>12,.2f}  ← cash actually disbursed')
print(f'    Sum of total_amount:     KES {Decimal(str(r["sum_total"] or 0)):>12,.2f}  ← what report currently shows')
print(f'    Difference:              KES {Decimal(str(r["sum_interest_fees"] or 0)):>12,.2f}  ← interest + fees inflating the total')
print()
print('  CONCLUSION: If the report shows "total_amount" as "loan amount given",')
print('  it will ALWAYS be higher than what admin calculates manually (which is')
print('  based on the actual cash disbursed = principal_amount).')

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