"""
Find if there's an older application for Faith's loan
"""
import pymysql

DB_CONFIG = {
    'host': 'localhost',
    'port': 3306,
    'database': 'xygbfpsg_loans',
    'user': 'xygbfpsg_graz',
    'password': 'j.ez-xy6##y.rllB',
    'charset': 'utf8mb4'
}

conn = pymysql.connect(**DB_CONFIG)

with conn.cursor() as cur:
    print("=" * 80)
    print("SEARCHING FOR FAITH'S ORIGINAL APPLICATION")
    print("=" * 80)
    
    # Get Faith's borrower ID
    borrower_id = '9467b3556a394985873b4b72261ef9e7'
    
    # Find ALL applications for Faith
    print("\n[INFO] Finding all applications for Faith...")
    cur.execute("""
        SELECT 
            application_number,
            requested_amount,
            submitted_at,
            status,
            id
        FROM loan_applications
        WHERE borrower_id = %s
        ORDER BY submitted_at ASC
    """, (borrower_id,))
    
    applications = cur.fetchall()
    
    print("\n[OK] Found {} application(s) for Faith:\n".format(len(applications)))
    
    for idx, (app_num, amount, submitted, status, app_id) in enumerate(applications, 1):
        print("{}. Application {}".format(idx, app_num))
        print("   Amount:    KES {:,.2f}".format(amount if amount else 0))
        print("   Submitted: {}".format(submitted))
        print("   Status:    {}".format(status))
        print("   ID:        {}".format(app_id))
        
        # Check if this application has a loan
        cur.execute("SELECT loan_number FROM loans WHERE application_id = %s", (app_id,))
        loan = cur.fetchone()
        if loan:
            print("   Loan:      {}".format(loan[0]))
        print()
    
    print("=" * 80)
    print("ANALYSIS:")
    print("=" * 80)
    
    if len(applications) == 1:
        print("\n⚠️  Only ONE application found (submitted 2026-11-19)")
        print("   This was likely created DURING the rollover")
        print("   The ORIGINAL application from March 2025 is MISSING")
        print("\n   Possible scenarios:")
        print("   1. Loan was created manually without an application")
        print("   2. Original application was deleted")
        print("   3. Rollover process created a new application")
        print("\n   Since you said original was KES 200,000:")
        print("   ✅ We should manually set original_disbursed_amount = 200000")
    
    elif len(applications) > 1:
        oldest = applications[0]
        print("\n✅ OLDEST application:")
        print("   Application: {}".format(oldest[0]))
        print("   Amount:      KES {:,.2f}".format(oldest[1] if oldest[1] else 0))
        print("   Submitted:   {}".format(oldest[2]))
        print("\n   This is likely the ORIGINAL disbursement amount")
        print("   Use this for original_disbursed_amount")
    
    else:
        print("\n❌ No applications found for Faith!")

conn.close()
