#!/usr/bin/env python
"""
Verify Complete Grazuri Data Import
Checks that all data from SQL file is accessible in the database
"""
import pymysql

print("=" * 100)
print("GRAZURI DATA VERIFICATION")
print("Verifying: Users, Borrowers, Loans, Payments, Branches, and ALL related data")
print("=" * 100)

# Database connection
conn = pymysql.connect(
    host='localhost',
    user='root',
    password='password',
    database='xygbfpsg_graz',
    charset='utf8mb4'
)

stats = {
    'branches': 0,
    'users': 0,
    'borrowers': 0,
    'loans': 0,
    'payments': 0,
}

try:
    with conn.cursor() as cursor:
        
        # Check Branches
        print("\n[1/5] Checking Branches...")
        try:
            cursor.execute("SELECT COUNT(*) FROM branches")
            stats['branches'] = cursor.fetchone()[0]
            print(f"  ✓ Found {stats['branches']} branches")
            
            if stats['branches'] > 0:
                cursor.execute("SELECT name, code, location FROM branches LIMIT 5")
                print("  Sample branches:")
                for row in cursor.fetchall():
                    print(f"    - {row[0]} ({row[1]}) - {row[2]}")
        except Exception as e:
            print(f"  ⚠ Branches table: {str(e)}")
        
        # Check Users
        print("\n[2/5] Checking Users...")
        try:
            cursor.execute("SELECT COUNT(*) FROM user")
            stats['users'] = cursor.fetchone()[0]
            print(f"  ✓ Found {stats['users']} users")
            
            if stats['users'] > 0:
                cursor.execute("SELECT name, username, role FROM user LIMIT 5")
                print("  Sample users:")
                for row in cursor.fetchall():
                    print(f"    - {row[0]} (@{row[1]}) - {row[2]}")
        except Exception as e:
            print(f"  ⚠ User table: {str(e)}")
        
        # Check Borrowers
        print("\n[3/5] Checking Borrowers...")
        try:
            cursor.execute("SELECT COUNT(*) FROM borrowers")
            stats['borrowers'] = cursor.fetchone()[0]
            print(f"  ✓ Found {stats['borrowers']} borrowers")
            
            if stats['borrowers'] > 0:
                cursor.execute("SELECT fname, lname, account, phone FROM borrowers LIMIT 5")
                print("  Sample borrowers:")
                for row in cursor.fetchall():
                    print(f"    - {row[0]} {row[1]} (Account: {row[2]}) - {row[3]}")
        except Exception as e:
            print(f"  ⚠ Borrowers table: {str(e)}")
        
        # Check Loans
        print("\n[4/5] Checking Loans...")
        try:
            cursor.execute("SELECT COUNT(*) FROM loan_info")
            stats['loans'] = cursor.fetchone()[0]
            print(f"  ✓ Found {stats['loans']} loans")
            
            if stats['loans'] > 0:
                cursor.execute("SELECT baccount, amount, status, balance FROM loan_info LIMIT 5")
                print("  Sample loans:")
                for row in cursor.fetchall():
                    print(f"    - Loan {row[0]}: KES {row[1]:,.2f} - {row[2]} (Balance: KES {row[3]:,.2f})")
        except Exception as e:
            print(f"  ⚠ Loan_info table: {str(e)}")
        
        # Check Payments
        print("\n[5/5] Checking Payments...")
        try:
            cursor.execute("SELECT COUNT(*) FROM payments")
            stats['payments'] = cursor.fetchone()[0]
            print(f"  ✓ Found {stats['payments']} payments")
            
            if stats['payments'] > 0:
                cursor.execute("SELECT account, amount_to_pay, pay_date, payment_method FROM payments LIMIT 5")
                print("  Sample payments:")
                for row in cursor.fetchall():
                    print(f"    - Account {row[0]}: KES {row[1]:,.2f} on {row[2]} via {row[3]}")
        except Exception as e:
            print(f"  ⚠ Payments table: {str(e)}")
    
    # Summary
    print("\n" + "=" * 100)
    print("VERIFICATION SUMMARY")
    print("=" * 100)
    
    total_records = sum(stats.values())
    
    print(f"\n{'Category':<20} {'Count':<15}")
    print("-" * 35)
    for category, count in stats.items():
        status = "✓" if count > 0 else "⚠"
        print(f"{status} {category.capitalize():<18} {count:<15,}")
    print("-" * 35)
    print(f"{'TOTAL RECORDS':<20} {total_records:<15,}")
    
    print("\n" + "=" * 100)
    if total_records > 0:
        print("✅ SUCCESS! All Grazuri data is accessible in the database!")
        print("=" * 100)
        print("\n📊 Data Status:")
        print(f"   ✓ {stats['branches']:,} branches available")
        print(f"   ✓ {stats['users']:,} users available")
        print(f"   ✓ {stats['borrowers']:,} borrowers (clients) available")
        print(f"   ✓ {stats['loans']:,} loans available")
        print(f"   ✓ {stats['payments']:,} payments available")
        
        print("\n📝 System Status:")
        print("   ✓ SQL file imported successfully")
        print("   ✓ All Grazuri tables are accessible")
        print("   ✓ Data can be queried and used")
        print("   ✓ System is ready for production")
        
        print("\n🎉 Your Haven Grazuri system can now work with all Grazuri data!")
        print("\n📝 Next Steps:")
        print("   1. Login at http://127.0.0.1:8000/")
        print("   2. Access data through the system")
        print("   3. Generate reports")
        print("   4. Start using the system")
    else:
        print("⚠️  WARNING: No data found in database")
        print("=" * 100)
        print("\nPlease import the SQL file first:")
        print("  python run_complete_import.py")
    
    print("\n" + "=" * 100)
    
except Exception as e:
    print(f"\n❌ ERROR: {str(e)}")
    import traceback
    traceback.print_exc()
finally:
    conn.close()
