#!/usr/bin/env python3
import pymysql
import uuid
from datetime import datetime

DB = dict(host='localhost', port=3306, database='xygbfpsg_loans',
          user='xygbfpsg_graz', password='j.ez-xy6##y.rllB',
          charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)

# Hardcoded test borrower data
BORROWER_ID = str(uuid.uuid4())
FIRST_NAME = 'John'
LAST_NAME = 'Doe'
ID_NUMBER = '12345678'
PHONE = '0712345678'
EMAIL = 'johndoe@example.com'
GENDER = 'male'
DATE_OF_BIRTH = '1990-01-01'
ADDRESS = 'Nairobi, Kenya'
OCCUPATION = 'Business Owner'
MONTHLY_INCOME = 50000.00
NEXT_OF_KIN = 'Jane Doe'
NEXT_OF_KIN_PHONE = '0723456789'
STATUS = 'active'

print("Creating test borrower...")

conn = pymysql.connect(**DB)
try:
    with conn.cursor() as cursor:
        # Find borrower table
        cursor.execute("SHOW TABLES LIKE '%borrower%'")
        tables = [list(t.values())[0] for t in cursor.fetchall()]
        
        if not tables:
            print("❌ No borrower table found!")
            print("Looking for client/customer tables...")
            cursor.execute("SHOW TABLES")
            all_tables = [list(t.values())[0] for t in cursor.fetchall()]
            print("Available tables:", ', '.join(all_tables[:20]))
            exit(1)
        
        table_name = tables[0]
        print(f"Using table: {table_name}")
        
        # Check structure
        cursor.execute(f"DESCRIBE {table_name}")
        columns = {col['Field']: col['Type'] for col in cursor.fetchall()}
        
        # Check if borrower exists
        cursor.execute(f"SELECT id FROM {table_name} WHERE id_number = %s OR phone_number = %s", 
                      (ID_NUMBER, PHONE))
        existing = cursor.fetchone()
        
        if existing:
            print(f"⚠️  Borrower already exists: {existing['id']}")
            BORROWER_ID = existing['id']
        else:
            print("Creating new borrower...")
            
            # Build insert based on available columns
            insert_data = {
                'id': BORROWER_ID,
                'first_name': FIRST_NAME,
                'last_name': LAST_NAME,
                'id_number': ID_NUMBER,
                'phone_number': PHONE,
                'email': EMAIL,
                'gender': GENDER,
                'date_of_birth': DATE_OF_BIRTH,
                'address': ADDRESS,
                'occupation': OCCUPATION,
                'monthly_income': MONTHLY_INCOME,
                'next_of_kin': NEXT_OF_KIN,
                'next_of_kin_phone': NEXT_OF_KIN_PHONE,
                'status': STATUS,
                'created_at': datetime.now(),
            }
            
            # Filter to only existing columns
            filtered_data = {k: v for k, v in insert_data.items() if k in columns}
            
            fields = ', '.join(filtered_data.keys())
            placeholders = ', '.join(['%s'] * len(filtered_data))
            values = list(filtered_data.values())
            
            sql = f"INSERT INTO {table_name} ({fields}) VALUES ({placeholders})"
            cursor.execute(sql, values)
            print("✅ Borrower created")
    
    conn.commit()
    
    # Verify
    with conn.cursor() as cursor:
        cursor.execute(f"SELECT * FROM {table_name} WHERE id = %s", (BORROWER_ID,))
        borrower = cursor.fetchone()
        
        if borrower:
            print("\n" + "="*60)
            print("✅ SUCCESS! TEST BORROWER CREATED")
            print("="*60)
            print(f"ID: {borrower['id']}")
            print(f"Name: {borrower['first_name']} {borrower['last_name']}")
            print(f"ID Number: {borrower['id_number']}")
            print(f"Phone: {borrower['phone_number']}")
            print(f"Email: {borrower['email']}")
            print(f"\nThis is a CLIENT RECORD (not a login user)")
            print(f"View at: https://grazuri.uzuriapps.xyz/borrowers/{BORROWER_ID}/")
            print("="*60)
        else:
            print("❌ Verification failed")
    
finally:
    conn.close()
