"""
fix_rollover_offset.py
----------------------
Sets rollover_payment_offset = 0 for all rolled-over loans.

The offset was hiding pre-rollover payments from the balance calculation,
making "Amount Repaid" show KES 0 even when repayments exist.

With offset = 0:
  amount_paid   = _amount_paid_cache (all repayments count)
  outstanding   = total_amount - amount_paid (payments reduce the balance)

Run on the server: python3 fix_rollover_offset.py
"""
import pymysql

DB_HOST     = "localhost"
DB_PORT     = 3306
DB_NAME     = "xygbfpsg_loans"
DB_USER     = "xygbfpsg_graz"
DB_PASSWORD = "j.ez-xy6##y.rllB"

conn = pymysql.connect(
    host=DB_HOST, port=DB_PORT, db=DB_NAME,
    user=DB_USER, password=DB_PASSWORD, charset="utf8mb4",
)

with conn.cursor() as cur:
    # Show current state
    cur.execute("""
        SELECT id, loan_number, principal_amount, total_amount,
               amount_paid, rollover_payment_offset
        FROM loans
        WHERE is_rolled_over = 1 AND is_deleted = 0
        ORDER BY created_at
    """)
    rows = cur.fetchall()

    print("=" * 80)
    print("  fix_rollover_offset.py")
    print("=" * 80)
    print(f"\nFound {len(rows)} rolled-over loan(s):\n")
    print(f"  {'Loan #':<22}  {'Principal':>10}  {'Total':>10}  {'Cache':>10}  {'Offset':>10}  {'Net Paid':>10}")
    print("  " + "-" * 75)

    for loan_id, loan_num, principal, total, cache, offset in rows:
        net = (cache or 0) - (offset or 0)
        print(f"  {str(loan_num):<22}  {float(principal or 0):>10,.0f}  {float(total or 0):>10,.0f}  {float(cache or 0):>10,.0f}  {float(offset or 0):>10,.0f}  {float(net):>10,.0f}")

    # Fix existing rolled-over loans:
    #   1. Set total_amount = principal_amount + interest_amount (interest now owed)
    #   2. Set rollover_payment_offset = 0 (all payments reduce balance)
    # NOTE: disbursement_date is intentionally NOT touched here — it must be
    #       set manually per loan using fix_rollover_disbursement_date.py
    cur.execute("""
        UPDATE loans
        SET rollover_payment_offset = 0,
            total_amount = principal_amount + interest_amount
        WHERE is_rolled_over = 1 AND is_deleted = 0
    """)
    conn.commit()

    print(f"\n  Set rollover_payment_offset = 0 for {cur.rowcount} loan(s) ✓")

    # Show new state
    cur.execute("""
        SELECT loan_number, amount_paid, rollover_payment_offset,
               total_amount
        FROM loans
        WHERE is_rolled_over = 1 AND is_deleted = 0
    """)
    print(f"\nAfter fix:")
    print(f"  {'Loan #':<22}  {'Cache':>10}  {'Offset':>8}  {'Total':>10}  {'Outstanding':>12}")
    print("  " + "-" * 65)
    for loan_num, cache, offset, total in cur.fetchall():
        outstanding = float(total or 0) - float(cache or 0)
        print(f"  {str(loan_num):<22}  {float(cache or 0):>10,.0f}  {float(offset or 0):>8,.0f}  {float(total or 0):>10,.0f}  {outstanding:>12,.0f}")

conn.close()
print(f"\n{'='*80}")
print("  Done. Repayments now subtract from the balance.")
print(f"{'='*80}")
