"""
fix_rollover_disbursement_date.py
----------------------------------
Shows all rolled-over loans with their current disbursement_date so you can
see which ones have the wrong date and manually correct them.

Also provides a way to set the correct original disbursement_date directly.

Run on the server: python3 fix_rollover_disbursement_date.py
"""
import pymysql
import sys

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",
    autocommit=False,
)

with conn.cursor() as cur:
    cur.execute("""
        SELECT
            l.id,
            l.loan_number,
            l.disbursement_date,
            l.created_at,
            l.principal_amount,
            l.interest_amount,
            l.total_amount,
            l.is_rolled_over,
            u.first_name,
            u.last_name,
            rr.requested_at AS rollover_requested_at,
            rr.reviewed_at  AS rollover_reviewed_at
        FROM loans l
        JOIN users u ON u.id = l.borrower_id
        LEFT JOIN rollover_requests rr
            ON rr.loan_id = l.id AND rr.status = 'approved'
        WHERE l.is_rolled_over = 1
          AND l.is_deleted = 0
        ORDER BY l.loan_number
    """)
    rows = cur.fetchall()

print("=" * 100)
print("  ROLLED-OVER LOANS — Disbursement Date Audit")
print("=" * 100)
print(f"\n{'Loan #':<22}  {'Borrower':<25}  {'Disb Date':<14}  {'Created':<14}  {'Total':>12}  {'P+I':>12}")
print("-" * 100)

for row in rows:
    (loan_id, loan_num, disb_date, created_at, principal, interest, total,
     is_rolled, fname, lname, rr_req, rr_rev) = row
    p_plus_i = float(principal or 0) + float(interest or 0)
    total_f = float(total or 0)
    disb_str = str(disb_date)[:10] if disb_date else 'NULL'
    created_str = str(created_at)[:10] if created_at else 'NULL'
    name = f"{fname or ''} {lname or ''}"[:24]
    total_ok = abs(total_f - p_plus_i) < 0.01
    print(f"{str(loan_num):<22}  {name:<25}  {disb_str:<14}  {created_str:<14}  "
          f"{total_f:>12,.2f}  {p_plus_i:>12,.2f}  {'✓' if total_ok else 'total WRONG'}")

print(f"\n{len(rows)} rolled-over loan(s) found.")
print()
print("To fix a loan's disbursement_date, run:")
print("  python3 fix_rollover_disbursement_date.py set <loan_number> <YYYY-MM-DD>")
print()

# Handle 'set' command
if len(sys.argv) == 4 and sys.argv[1] == 'set':
    loan_number = sys.argv[2]
    new_date    = sys.argv[3]
    with conn.cursor() as cur:
        cur.execute(
            "UPDATE loans SET disbursement_date=%s WHERE loan_number=%s AND is_rolled_over=1",
            [new_date, loan_number]
        )
        if cur.rowcount:
            conn.commit()
            print(f"  Updated {loan_number} disbursement_date → {new_date} ✓")
        else:
            print(f"  No rolled-over loan found with number {loan_number}")

conn.close()
